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

前端 未结 5 1250
闹比i
闹比i 2020-12-07 12:48

I have an NSFetchRequest which is returning the objects\' properties in an NSDictionaryResultType. Is it possible to also get the objects\' ObjectI

5条回答
  •  渐次进展
    2020-12-07 13:23

    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.

提交回复
热议问题