small medium large xlarge

Generic-user-small
09 Feb 2013, 02:51
Tim West (4 posts)

In section 4.3 when talking about fetching data you describe how to get only NSManagedObjectIDs and how this is a super fast way to query the database. I am wondering if you could elaborate on the use of this method to check if an object with a certain identifier is already in the object graph and if it is load the full object.

Would NSManagedObjectID be a good way to do this?

If so what would the implementation look like?

Avatarsmall_pragsmall
13 Feb 2013, 18:31
Marcus S. Zarra (285 posts)

First, I would not recommend using the @NSManagedObjectID@ as a unique identifier. It can and does change during the life of an application and should not be relied upon from one run of the application to another.

I would recommend creating your own non-changing unique identifier and then executing a count against it and then reacting based on the results of that count.

Generic-user-small
16 Feb 2013, 21:12
Tim West (4 posts)

Thanks Marcus - when you say issuing a count that involves setting up a fetch request for the unique identifier and checking if we get any objects right?

Avatarsmall_pragsmall
18 Feb 2013, 16:52
Marcus S. Zarra (285 posts)

Close, it would be something like:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"MyEntity"];
[request setPredicate:[NSPredicate predicateWithFormat:@"uniqueKey == %@", someKey]];
NSError *error = nil;
NSInteger count = [moc countForFetchRequest:request error:&error];
if (count == NSNotFound) {
  NSLog(@"Error: %@\n%@", [error localizedDescription], [error userInfo]);
}
if (count == 0) {
  NSLog(@"Record does not exist");
}

You could also pre-fetch the unique rows if you knew which ones you were going to be processing:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"MyEntity"];
[request setPredicate:[NSPredicate predicateWithFormat:@"uniqueKey IN %@", someKeyArray]];
NSError *error = nil;
NSArray *toBeUpdatedArray = [moc executeFetchRequest:request error:&error];
if (!toBeUpdatedArray) {
  NSLog(@"Error: %@\n%@", [error localizedDescription], [error userInfo]);
}
NSDictionary *toBeUpdatedDictionary = [NSDictionary dictionaryWithObjects:toBeUpdatedArray forKeys:[toBeUpdatedArray valueForKey:@"uniqueKey"]];

Then you end up with a dictionary @toBeUpdatedDictionary@ that has the unique as the key and as you iterate over the objects you can grab them from the dictionary and update them.