Searching for an id in Core Data - iphone

I am getting some unexpected behavior with CoreData and NSPredicate. In a large database population I have different Managed Objects relating to one-another. However, I have a problem with the following. When giving an id (NSNumber, given as NSString to this function) I don't get a result unless I save the whole context first. I don;t want to do that as it takes too much time (as it is a large set of data). The code is:
- (DOSite *) findSite:(NSString *) siteId {
NSPredicate* predicate = [NSPredicate predicateWithFormat:#"(id = %#)", siteId];
[NSFetchedResultsController deleteCacheWithName:nil];
[[self fetchedResultsController].fetchRequest setPredicate:predicate];
NSError *fetchError;
if (![[self fetchedResultsController] performFetch:&fetchError]) {
// Handle the error.
// This is a serious error and should advise the user to restart the application
NSLog(#"Fetching data error: %#", [fetchError localizedDescription]);
}
if([[[self fetchedResultsController] fetchedObjects] count] == 0){
return NULL;
}
return (DOSite *)[[[self fetchedResultsController] fetchedObjects] objectAtIndex:0];
}
So when I add an x number of items (using +[NSEntityDescription insertNewObjectForEntityForName:inManagedObjectContext:]) doing a search on all items return the right amount of items.
When searching for a string (e.g.predicateWithFormat:#"(name LIKE %#)") I get positive results, but when using the above code predicateWithFormat:#"(id = %#) I get zero results.
The only way I can get results is to save the whole context and then perform the fetchRequest, then suddenly it works.
So there must be something small I do wrong in searching for the id, I just seem to be blind to find it and spend two days at it now to narrow it down to this point. Is there anybody who can give me some advice on this?

This may not work, but have you tried using a name more complex than "id" in your entity (like "SiteID")? Sometimes very short names overlap with other system properties and it causes odd issues.

The problem was that I gave a NSString to the predicate as outlined above. When changing that to an int (ie predicateWithFormat:#"(id == %i)") it works fine for some reason.

Related

How to Efficiently Reset Attributes in a Core Data Entity

My app uses Core Data and has an attribute called 'beenSeen'. When a user refreshes the app, all 'beenSeen' values of 1 are changed to 0. On an iPod Touch 2nd gen with over 2000 objects, refreshing takes over a minute. My code looks like this:
for (Deck *deck in self.deckArray) {
if ([deck.beenSeen isEqualToNumber:[NSNumber numberWithInt:1]]) {
[deck setBeenSeen:[NSNumber numberWithInt:0]];
[self.managedObjectContext save:&error];
}
}
I'm also considering deleting the sqlite file and having an alert ask the user to restart the app themselves. Doing that sure is a whole lot quicker than what I have now. Is there a quicker way to refresh an entity? Could I have a 'backup' entity and copy it over? Thanks for any help.
Hm. The first optimization I'd suggest would be
for (Deck *deck in self.deckArray) {
if ([deck.beenSeen isEqualToNumber:[NSNumber numberWithInt:1]]) {
[deck setBeenSeen:[NSNumber numberWithInt:0]];
}
}
[self.managedObjectContext save:&error];
I suspect it might speed things up to do one big context save, instead of 2,000 little ones.
The second suggestion would be to try getting rid of the if test – if the majority of your beenSeen values are changing from 1 to 0, and the others are already 0, then you might as well just set all of them to 0 and save the time of checking each one individually. (On the other hand, if there are 10,000 objects and you're resetting 2,000 of them, then getting rid of the test might not be optimal.)
for (Deck *deck in self.deckArray) {
[deck setBeenSeen:[NSNumber numberWithInt:0]];
}
[self.managedObjectContext save:&error];
}
The third suggestion would be to think about implementing this another way – for instance, your deck object could implement a lastSeen attribute, storing the date and time when the deck was last seen, and then instead of doing a mass reset (and writing 2,000 Core Data rows) you could just test each deck's lastSeen date and time against the timestamp of the last user refresh.
Try this, First, filter the array using a predicate:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"beenSeen == %#",
[NSNumber numberWithInt:1]];
NSArray* filtered = [self.deckArray filteredArrayUsingPredicate:predicate];
Now set the new value:
[filtered setValue:[NSNumber numberWithInt:0] forKeyPath:#"beenSeen"];
Finally save the context:
[self.managedObjectContext save:&error];
Hope this helps :)

iPhone SDK Core Data relationships problem

I'm having a problem with relationships between to entities in Core Data. I'm parsing some JSON and adding the entities:
if ([hourSets isKindOfClass:[NSArray class]]) { // check to see that we have got some hours back
for (NSDictionary *hourSet in hourSets) {
Hourset *thisHourSet = (Hourset *)[NSEntityDescription
insertNewObjectForEntityForName:#"Hourset"
inManagedObjectContext:managedObjectContext];
[thisHourSet setStartDate:[hourSet objectForKey:#"start_date"]];
[thisHourSet setEndDate:[hourSet objectForKey:#"end_date"]];
[record addHoursetsObject:thisHourSet];
}
}
...and then later trying to grab them again:
NSSet *hourSets = [self.listing valueForKeyPath:#"hoursets.hourset"];
NSLog(#"There are %# hourSets", [hourSets count]);
I'm getting Program received signal: “EXC_BAD_ACCESS”. when trying to access that hourSets NSSet in any way, including just counting the items in it.
Any suggestions? Pretty stumped. Thanks!
I am inferring your entity graph here but:
[self.listing valueForKeyPath:#"hoursets.hourset"]
... translates to a keypath of listing.hoursets.hourset which does not appear to return a set. Both the first and last elements are singular and therefore by convention not sets.
I would suggest logging the class of the return to confirm what, if anything, you're getting back.
Update:
(Forehead slap) The problem is actually the log statement itself. It should be:
NSLog(#"There are %d hourSets", [hourSets count]);
... because count returns an NSUInteger.

Cocoa Core Data - Efficient Related Entities Counts

I am working on my first iPhone application and I've hit a wall. I'm trying to develop a 'statistics' page for a three entity relationship. My entities are the following:
Department - Name, Address, Building, etc.
People - Name, Gender (BOOL), Phone, etc
If I have fetched a specific department how do I filter those results and only return people that are Male (Gender == 0)?
If I do
NSLog(#"%d", [department.people count]);
I get the correct number of people in that department so I know I'm in the neighborhood. I know I could re-fetch and modify the predicate each time but with 20+ stats in my app that seems inefficient. Thanks for any advice!
You don't need to refetch:
NSPredicate* pred = [NSPredicate predicateWithFormat:#"gender == NO"];
NSUInteger count = [[department.people filteredArrayUsingPredicate:pred] count];
NSLog(#"%lu", (unsigned long)count);
Somehow gender==NO still looks strange though ;)
If copying is too expensive, you could use enumerators instead. E.g.:
NSUInteger CountIf(NSEnumerator* en, NSPredicate* pred) {
NSUInteger count = 0;
id obj;
while (obj = [en nextObject]) {
if([pred evaluateWithObject:obj])
++count;
}
return count;
}
NSUInteger count = CountIf([department.people objectEnumerator], predicate));
... though this would be ideally moved to a suitable category as say countOfObjectsMatchingPredicate:.
You could create NSPredicates representing your different filters and use NSSet's filteredSetWithPredicate: method. The count method will give you the number of entities matching the predicate. This isn't terribly efficient because you're creating a new set for each calculation, but it may be significantly faster than fetching each time.

iphone Core Data Unresolved error while saving

I am getting a strange error message from the core data when trying to save
but the problem that the error is not reproducible ( it appears at different times when doing different tasks)
the error message:
Unresolved error Domain=NSCocoaErrorDomain Code=1560 UserInfo=0x14f5480 "Operation could not be completed. (Cocoa error 1560.)", {
NSDetailedErrors = (
Error Domain=NSCocoaErrorDomain Code=1570 UserInfo=0x5406d70 "Operation could not be completed. (Cocoa error 1570.)",
Error Domain=NSCocoaErrorDomain Code=1570 UserInfo=0x14f9be0 "Operation could not be completed. (Cocoa error 1570.)"
);
}
and the method that generates the error is:
- (IBAction)saveAction:(id)sender {
NSError *error;
if (![[self managedObjectContext] save:&error]) {
// Handle error
NSLog(#"Unresolved error %#, %#, %#", error, [error userInfo],[error localizedDescription]);
exit(-1); // Fail
}
}
any idea for the reason of this message ? giving that it appears at random times
It means there's a mandatory property has been assigned nil. Either in your *.xcodatamodel check the "optional" box or when you are saving to the managedObjectContext make sure that your properties are filled in.
If you're getting further errors after changing your code to suit the two requirements try cleaning your build and delete the application from your iPhone Simulator/iPhone device. Your model change may conflict with the old model implementation.
Edit:
I almost forgot here's all the error codes that Core Data spits out:
Core Data Constants Reference
I had trouble with this before and I realised I unchecked the correct optional box. Such trouble finding out the problem. Good luck.
I struggled with this for a little while myself. The real problem here is that the debugging you've got isn't showing you what the problem is. The reason for this is because CoreData will put an array of NSError objects in the "top level" NSError object it returns if there is more than one problem (This is why you see error 1560, which indicates multiple problems, and an array of error 1570s). It appears that CoreData has a handful of keys it uses to stash information in the error it returns if there is an issue that will give you more useful information (Such as the entity the error occurred on, the relationship/attribute that was missing, etc). The keys you use to inspect the userInfo dictionary can be found in the reference docs here.
This is the block of code I use to get reasonable output from the error returned during a save:
NSError* error;
if(![[survey managedObjectContext] save:&error]) {
NSLog(#"Failed to save to data store: %#", [error localizedDescription]);
NSArray* detailedErrors = [[error userInfo] objectForKey:NSDetailedErrorsKey];
if(detailedErrors != nil && [detailedErrors count] > 0) {
for(NSError* detailedError in detailedErrors) {
NSLog(#" DetailedError: %#", [detailedError userInfo]);
}
}
else {
NSLog(#" %#", [error userInfo]);
}
}
It will produce output that tells you the fields that are in missing, which makes fixing the problem significantly easier to deal with.
I'm throwing this in as an answer, even though it's really more of an embellishment to Charles' snippet. The straight output from NSLog can be a mess to read and interpret, so I like to throw in some white space and call out the value of some critical 'userInfo' keys.
Here's a version of the method I've been using. ('_sharedManagedObjectContext' is a #define for '[[[UIApplication sharedApplication] delegate] managedObjectContext]'.)
- (BOOL)saveData {
NSError *error;
if (![_sharedManagedObjectContext save:&error]) {
// If Cocoa generated the error...
if ([[error domain] isEqualToString:#"NSCocoaErrorDomain"]) {
// ...check whether there's an NSDetailedErrors array
NSDictionary *userInfo = [error userInfo];
if ([userInfo valueForKey:#"NSDetailedErrors"] != nil) {
// ...and loop through the array, if so.
NSArray *errors = [userInfo valueForKey:#"NSDetailedErrors"];
for (NSError *anError in errors) {
NSDictionary *subUserInfo = [anError userInfo];
subUserInfo = [anError userInfo];
// Granted, this indents the NSValidation keys rather a lot
// ...but it's a small loss to keep the code more readable.
NSLog(#"Core Data Save Error\n\n \
NSValidationErrorKey\n%#\n\n \
NSValidationErrorPredicate\n%#\n\n \
NSValidationErrorObject\n%#\n\n \
NSLocalizedDescription\n%#",
[subUserInfo valueForKey:#"NSValidationErrorKey"],
[subUserInfo valueForKey:#"NSValidationErrorPredicate"],
[subUserInfo valueForKey:#"NSValidationErrorObject"],
[subUserInfo valueForKey:#"NSLocalizedDescription"]);
}
}
// If there was no NSDetailedErrors array, print values directly
// from the top-level userInfo object. (Hint: all of these keys
// will have null values when you've got multiple errors sitting
// behind the NSDetailedErrors key.
else {
NSLog(#"Core Data Save Error\n\n \
NSValidationErrorKey\n%#\n\n \
NSValidationErrorPredicate\n%#\n\n \
NSValidationErrorObject\n%#\n\n \
NSLocalizedDescription\n%#",
[userInfo valueForKey:#"NSValidationErrorKey"],
[userInfo valueForKey:#"NSValidationErrorPredicate"],
[userInfo valueForKey:#"NSValidationErrorObject"],
[userInfo valueForKey:#"NSLocalizedDescription"]);
}
}
// Handle mine--or 3rd party-generated--errors
else {
NSLog(#"Custom Error: %#", [error localizedDescription]);
}
return NO;
}
return YES;
}
This allows me to see the value for 'NSValidationErrorKey', which, when I encountered the issue from the OP, pointed directly to the non-optional Core Data entities that I'd forgot to set before trying to save.
The problem touched me, when I save second record to CoreData.
All not optional fields (relationship) was filled without nil as well, but in the error output I'd notice, that one of fields in first saved object had became nil. Strange a little? But the reason is quite trivial - one to one relationship which nullify first object, when I set it in the second.
So, the scheme is:
"Parent" with relationship "child" One to One
Create Child 1, set parent. Save - OK
Create Child 2, set parent. Save - Error, Child 1.Parent == nil
(behind the scene child 2 did nullify child 1 parent)
Changing the relationship in Parent from One to One to Many to One solved this task.
I had transient property of type int that wasn't optional. Obviously, when it was set to 0, 1570 error appear. Just changed all my transient properties to optional. Nil-check logic can be implemented in code if necessary.
I means that your model failed to validate, which could happen for a number of reasons: unused property in your model, missing value that's marked as required.
To get a better understanding of what exactly went wrong, put a breakpoint in a place where you are ready to save your object, and call one of the validateFor... method variants, like:
po [myObject validateForInsert]
More detailed information about the problem is in error description. Successful validation means you will get no output.
It helped me. Check this one too.
Check the optional box in your *.xcodatamodel objects

Bulk update & occasional insert (coredata) - Too slow

Update: Currently looking into NSSET's minusSet
links: Comparing Two Arrays
Hi guys,
Could benefit from your wisdom here..
I'm using Coredata in my app, on first launch I download a data file and insert over 500 objects (each with 60 attributes) - fast, no problem.
Each subsequent launch I download an updated version of the file, from which I need to update all existing objects' attributes (except maybe 5 attributes) and create new ones for items which have been added to the downloaded file.
So, first launch I get 500 objects.. say a week later my file now contains 507 items..
I create two arrays, one for existing and one for downloaded.
NSArray *peopleArrayDownloaded = [CoreDataHelper getObjectsFromContext:#"person" :#"person_id" :YES :managedObjectContextPeopleTemp];
NSArray *peopleArrayExisting = [CoreDataHelper getObjectsFromContext:#"person" :#"person_id" :YES :managedObjectContextPeople];
If the count of each array is equal then I just do this:
NSUInteger index = 0;
if ([peopleArrayExisting count] == [peopleArrayDownloaded count]) {
NSLog(#"Number of people downloaded is same as the number of people existing");
for (person *existingPerson in peopleArrayExisting) {
person *tempPerson = [peopleArrayDownloaded objectAtIndex:index];
// NSLog(#"Updating id: %# with id: %#",existingPerson.person_id,tempPerson.person_id);
// I have 60 attributes which I to update on each object, is there a quicker way other than overwriting existing?
index++;
}
} else {
NSLog(#"Number of people downloaded is different to number of players existing");
So now comes the slow part.
I end up using this (which is tooooo slow):
NSLog(#"Need people added to the league");
for (person *tempPerson in peopeArrayDownloaded) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"person_id = %#",tempPerson.person_id];
// NSLog(#"Searching for existing person, person_id: %#",existingPerson.person_id);
NSArray *filteredArray = [peopleArrayExisting filteredArrayUsingPredicate:predicate];
if ([filteredArray count] == 0) {
NSLog(#"Couldn't find an existing person in the downloaded file. Adding..");
person *newPerson = [NSEntityDescription insertNewObjectForEntityForName:#"person" inManagedObjectContext:managedObjectContextPeople];
Is there a way to generate a new array of index items referring to the additional items in my downloaded file?
Incidentally, on my tableViews I'm using NSFetchedResultsController so updating attributes will call [cell setNeedsDisplay];
.. about 60 times per cell, not a good thing and it can crash the app.
Thanks for reading :)
I'll begin by saying that I'm still new to using the Core Data framework, but my guess is that your problem lies in the for loop you've posted.
If you look at your loop, each time it executes it creates a new NSPredicate object and then filters your existing array looking for matches. On a small data set this technique would work with seemingly small performance losses; however, with your large data set you will end up spending a lot of time creating NSPredicate objects that only differ in the name you've provided. I would suggest that you look at how to create a single predicate and then use variable substitution to perform the search. For information about variable use in predicates check out: http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/CoreData/Articles/cdImporting.html#//apple_ref/doc/uid/TP40003174
As a side note, you may also consider how you've sorted your data and how you are performing the search operation. And another thing I noticed is that you don't release your NSPredicate object, so you're just tossing memory away too.