36

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

4

5 回答 5

81

是的,你可以,使用非常漂亮但记录不充分的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];

然后,您应该@"objectID"在从获取请求中返回的字典中有一个键。

于 2011-01-25T10:25:00.750 回答
4
 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"]);

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

于 2011-03-15T19:23:51.163 回答
1

Nick Hutchinson 在 Swift 中的回答:

    let idDescription = NSExpressionDescription()
    idDescription.name = "objectID"
    idDescription.expression = NSExpression.expressionForEvaluatedObject()
    idDescription.expressionResultType = .objectIDAttributeType

我无法对此发表评论,因为我没有足够的代表:(

于 2016-01-02T01:40:11.173 回答
0

已接受答案的 Swift 版本

    let objectIDExpression = NSExpressionDescription()
    objectIDExpression.name = "objectID"
    objectIDExpression.expression = NSExpression.expressionForEvaluatedObject()
    objectIDExpression.expressionResultType = .objectIDAttributeType
    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entityName)
    fetchRequest.resultType = .dictionaryResultType
    //
    var propertiesToFetch: [Any] = [objectIDExpression]
    propertiesToFetch.append(contentsOf: entity.properties)
    fetchRequest.propertiesToFetch = propertiesToFetch
于 2020-11-23T07:42:48.027 回答
-1

到目前为止,我发现的唯一解决方案是执行第二个 fetch 请求,这类似于初始 fetch 请求,但有以下区别:

[fetchRequest setReturnsObjectsAsFaults:YES];
[fetchRequest setPropertiesToFetch:nil];
[fetchRequest setFetchLimit:1];
[fetchRequest setFetchOffset:index]; // The index for which the objectID is needed
[request setResultType:NSManagedObjectIDResultType];

这将导致获取请求返回一个数组,其中只有一个对象,即所需的 objectID。性能似乎不错,即使初始提取请求的结果包含 10000 个对象。

如果有更好的方法来处理这个问题,如果有人可以在这里发布它们,我会很高兴。

于 2010-12-22T23:54:09.143 回答