【发布时间】:2011-04-26 18:21:18
【问题描述】:
我有一个NSFetchRequest,它在NSDictionaryResultType 中返回对象的属性。是否也可以在此字典中获取对象的 ObjectId?否则我将需要以NSManagedObjectResultType 的返回类型运行查询,这对于大量返回的项目来说要慢得多。
【问题讨论】:
标签: iphone core-data ios nsfetchrequest
我有一个NSFetchRequest,它在NSDictionaryResultType 中返回对象的属性。是否也可以在此字典中获取对象的 ObjectId?否则我将需要以NSManagedObjectResultType 的返回类型运行查询,这对于大量返回的项目来说要慢得多。
【问题讨论】:
标签: iphone core-data ios nsfetchrequest
已接受答案的 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
【讨论】:
Nick Hutchinson 在 Swift 中的回答:
let idDescription = NSExpressionDescription()
idDescription.name = "objectID"
idDescription.expression = NSExpression.expressionForEvaluatedObject()
idDescription.expressionResultType = .objectIDAttributeType
我无法对此发表评论,因为我没有足够的代表:(
【讨论】:
目前我发现的唯一解决方案是执行第二个获取请求,这与初始获取请求类似,但有以下区别:
[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 个对象。
如果有任何更好的方法来处理这个问题,如果有人可以在这里发布它们,我会很高兴。
【讨论】:
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" 将它们拉出来呢?干净、简单只需要一个获取请求,因此您也可以提取您需要的所有其他数据。
【讨论】:
是的,您可以使用非常漂亮但记录不充分的 NSExpressionDescription 类。您需要将正确配置的NSExpressionDescription 对象添加到您通过setPropertiesToFetch: 为NSFetchRequest 设置的NSPropertyDescription 对象数组中。
例如:
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" 键。
【讨论】: