[英]How to use Coredata ordered relationships with NSFetchedResultsController
I want to fetch all Items for a Tag using a NSFetchedResultsController. 我想使用NSFetchedResultsController获取标签的所有项目。
Queries: 查询:
Did not work: [NSPredicate predicateWithFormat:@"ANY tags == %@", yyy]; 没有用:[NSPredicate predicateWithFormat:@“ANY tags ==%@”,yyy];
Worked: But less efficient: [NSPredicate predicateWithFormat:@"ANY tags.tagID == %@", xxx]; 工作:但效率较低:[NSPredicate predicateWithFormat:@“ANY tags.tagID ==%@”,xxx];
1 - Yes. 1 - 是的 It is possible.
有可能的。 When you create your mapping file, make sure you change the relationship's type from an NSSet to an NSArray, like so:
创建映射文件时,请确保将关系的类型从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
Change to: 改成:
@class Tags
@interface Entity : NSManagedObject
...
@property (nonatomic, retain) NSArray *tags;
...
@end
@interface Entity (CoreDataGeneratedAccessors)
...
- (void)addEntityTags:(NSArray *)values;
- (void)removeEntityTags:(NSArray *)values;
...
@end
2 - You can specify a sort descriptor when creating your fetch request, like so: 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 - If you use the property, you shouldn't need to specify a predicate for your tags. 3 - 如果使用该属性,则不需要为标记指定谓词。 If you want to further sort your tags, you can simply use a sort descriptor on that array, like this:
如果要进一步对标记进行排序,可以在该数组上使用排序描述符,如下所示:
NSSortDescriptor *tagDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"<tags field to sort on>" ascending:<YES|NO>];
NSArray *sortedTags = [tagsProperty sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptors]];
You can simply read from that property for your tags. 您只需从该属性中读取标签即可。
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.