我想使用NSFetchedResultsController获取标记的所有项目。
查询:
无效:[NSPredicate predicateWithFormat:@“ANY tags ==%@”,yyy];
工作:但效率较低:[NSPredicate predicateWithFormat:@“ANY tags.tagID ==%@”,xxx];
答案 0 :(得分:2)
1 - 是的。有可能的。创建映射文件时,请确保将关系的类型从NSSet更改为NSArray,如下所示:
@class Tags
@interface Entity : NSManagedObject
...
@property (nonatomic, retain) NSOrderedSet *tags;
...
@end
@interface Entity (CoreDataGeneratedAccessors)
...
- (void)addEntityTags:(NSOrderedSet *)values;
- (void)removeEntityTags:(NSOrderedSet *)values;
...
@end
更改为:
@class Tags
@interface Entity : NSManagedObject
...
@property (nonatomic, retain) NSArray *tags;
...
@end
@interface Entity (CoreDataGeneratedAccessors)
...
- (void)addEntityTags:(NSArray *)values;
- (void)removeEntityTags:(NSArray *)values;
...
@end
2 - 您可以在创建获取请求时指定排序描述符,如下所示:
NSFetchRequest *fetchRequest [NSFetchRequest new];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity" inManagedObjectContext:myManagedObjectContext];
[fetchRequest.setEntity: entity];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"tags" ascending:<YES|NO>]];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"ANY tags == %@", yyy]];
NSFetchResultsController *myFetchResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:myManagedObjectContext setcionNameKeyPath:nil cacheName:nil];
myFetchResultsController.delegate = self;
[fetchRequest release]; // Forget that if using ARC.
NSError *error = nil;
if (![myFetchResultsController performFetch:&error]) {
NSLog(@"Failed to fetch data: %@", error);
}
3 - 如果使用该属性,则不需要为标记指定谓词。如果要进一步对标记进行排序,可以在该数组上使用排序描述符,如下所示:
NSSortDescriptor *tagDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"<tags field to sort on>" ascending:<YES|NO>];
NSArray *sortedTags = [tagsProperty sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptors]];
您只需从该属性中读取标签即可。
希望这有帮助!