Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core data, how to get NSManagedObject's ObjectId when NSFetchRequest returns NSDictionaryResultType?

I have an NSFetchRequest which is returning the objects' properties in an NSDictionaryResultType. Is it possible to also get the objects' ObjectId within this dictionary? Otherwise I will need to run the query with a return type of NSManagedObjectResultType which is much slower for a large number of returned items.

like image 811
Jason Avatar asked Oct 18 '10 03:10

Jason


2 Answers

Yes you can, using the very nifty but badly-documented NSExpressionDescription class. You need to add a properly-configured NSExpressionDescription object to the array of NSPropertyDescription objects you set via setPropertiesToFetch: for your NSFetchRequest.

For example:

NSExpressionDescription* objectIdDesc = [[NSExpressionDescription new] autorelease]; objectIdDesc.name = @"objectID"; objectIdDesc.expression = [NSExpression expressionForEvaluatedObject]; objectIdDesc.expressionResultType = NSObjectIDAttributeType;  myFetchRequest.propertiesToFetch = [NSArray arrayWithObjects:objectIdDesc, anotherPropertyDesc, yetAnotherPropertyDesc, nil]; NSArray* fetchResults = [myContext executeFetchRequest:myFetchRequest error:&fetchError]; 

You should then have a @"objectID" key in the the dictionaries you get back from your fetch request.

like image 89
Nick Hutchinson Avatar answered Sep 30 '22 11:09

Nick Hutchinson


 NSFetchRequest *request = [[NSFetchRequest alloc] init];     request.entity = [NSEntityDescription entityForName:@"yourEntity" inManagedObjectContext:context];     request.sortDescriptors = [NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES], nil];     request.predicate = nil;     request.fetchLimit = 20;      NSError *error = nil;     NSArray fetchedResults = [context executeFetchRequest:request error:&error];      NSLog(@"%@", [fetchedResults valueForKey:@"objectID"]); 

Since your fetched results are already in an array why not pull them out with the valueForKey:@"objectID" ? Clean, simple only need one fetch request so you can pull all other data you need as well.

like image 33
Michael Shaw Avatar answered Sep 30 '22 12:09

Michael Shaw