我有一个包含相关对象的NSManagedObject
。这种关系由keyPath描述。
现在,我想在表视图中显示这些相关对象。当然,我可以只将具有这些对象的NSSet
作为数据源,但我更喜欢使用NSFetchedResultsController
重新获取对象,以便从其特性中受益。
如何创建描述这些对象的谓词?
发布于 2013-09-01 18:19:54
要使用fetched results控制器显示给定对象的相关对象,您可以在谓词中使用反向关系。例如:
要显示与给定父项相关的子项,请使用带有以下fetch请求的fetched results控制器:
Parent *theParent = ...;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Child"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"parent = %@", theParent];
[request setPredicate:predicate];
对于嵌套关系,只需按相反顺序使用反向关系即可。示例:
要显示给定国家的街道,请执行以下操作:
Country *theCountry = ...;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Street"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"city.country = %@", theCountry];
[request setPredicate:predicate];
发布于 2013-09-01 19:09:55
谢谢马丁,你给了我重要的信息。
为了获得关键路径,我找到了以下实现:
// assume to have a valid key path and object
NSString *keyPath;
NSManagedObject *myObject;
NSArray *keys = [keyPath componentsSeparatedByString:@"."];
NSEntityDescription *entity = myObject.entity;
NSMutableArray *inverseKeys = [NSMutableArray arrayWithCapacity:keys.count];
// for the predicate we will need to know if we're dealing with a to-many-relation
BOOL isToMany = NO;
for (NSString *key in keys) {
NSRelationshipDescription *inverseRelation = [[[entity relationshipsByName] valueForKey:key] inverseRelationship];
// to-many on multiple hops is not supported.
if (isToMany) {
NSLog(@"ERROR: Cannot create a valid inverse relation for: %@. Hint: to-many on multiple hops is not supported.", keyPath);
return nil;
}
isToMany = inverseRelation.isToMany;
NSString *inverseKey = [inverseRelation name];
[inverseKeys insertObject:inverseKey atIndex:0];
}
NSString *inverseKeyPath = [inverseKeys componentsJoinedByString:@"."];
// now I can construct the predicate
if (isToMany) {
predicate = [NSPredicate predicateWithFormat:@"ANY %K = %@", inverseKeyPath, self.dataObject];
}
else {
predicate = [NSPredicate predicateWithFormat:@"%K = %@", inverseKeyPath, self.dataObject];
}
更新:我更改了谓词格式,以便它也支持多对多关系。
更新2这变得越来越复杂:我需要检查我的逆关系是否为to -并使用不同的谓词。我更新了上面的代码示例。
发布于 2014-07-04 17:47:16
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"city.country = '%@'", theCountry];
在predicateWithFormat字符串中遗漏了‘’。现在它起作用了。
https://stackoverflow.com/questions/18560936
复制相似问题