核心数据,当NSFetchRequest返回NSDictionaryResultType时如何获取NSManagedObject的ObjectId?

Jas*_*son 34 iphone core-data nsfetchrequest ios

我有一个NSFetchRequest返回对象的属性NSDictionaryResultType.是否有可能在这个字典中获取对象的ObjectId?否则,我将需要运行返回类型的查询,NSManagedObjectResultType对于大量返回的项目,返回类型要慢得多.

Nic*_*son 78

是的,你可以使用非常漂亮但记录严重的NSExpressionDescription课程.您需要将正确配置的NSExpressionDescription对象添加到NSPropertyDescriptionsetPropertiesToFetch:为其设置的对象数组中NSFetchRequest.

例如:

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];
Run Code Online (Sandbox Code Playgroud)

然后,您应该@"objectID"在从获取请求中获取的词典中有一个键.

  • 很高兴找到尼克,你非常感谢你记录这个例子. (2认同)

小智 5

 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"]);
Run Code Online (Sandbox Code Playgroud)

既然您获取的结果已经在数组中,为什么不使用 valueForKey:@"objectID" 将它们取出?干净、简单,只需要一个提取请求,这样您就可以提取您需要的所有其他数据。