在我的应用程序中,我有两个实体:成员和列表 . 它们都有一对多关系(成员可以有多个列表,列表可以有多个成员) . 现在我想获取属于特定成员的列表 . 这是我的代码:
WSAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Lists" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"has_members contains[cd] %@", [self.currentMember valueForKey:@"name"]]];
[fetchRequest setPredicate:predicate];
NSError *error;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
// Handle the error.
NSLog(@"NO LISTS AVAILABLE IN REFRESH");
}
self.currentMember是用户自己的托管对象 .
注意:成员有名称,(NSSet *)member_of_list
list有list_name,has-members
问题:当我运行代码时,它会破坏fetchedObjects数组 . 我怀疑NSPredicate有问题,但我不知道在哪里以及如何解决它 . 任何人都可以指出问题吗?
1 回答
首先,您描述的关系
Member
(以复数形式调用实体令人困惑)和List
是多对多关系 .其次,不是使用CoreData的固有对象图功能,而是实体之间的关系(你应该使用你的界面构建器来模拟两个实体之间的CoreData关系) .
见HERE如何做到这一点 .
在对数据建模之后,您的谓词应该类似于:
DO NOT 传递格式化字符串以创建谓词,使用
NSPredicate
格式替换参数,否则您将无法实现目标(在大多数情况下) .