核心数据获取关系对象

时间:2013-12-26 16:57:55

标签: ios core-data

在我的应用中,我有两个实体:成员和列表。它们都有一对多关系(成员可以有多个列表,列表可以有多个成员)。现在我想获取属于特定成员的列表。这是我的代码:

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 个答案:

答案 0 :(得分:3)

首先,您在Member之间描述的关系(以复数形式调用实体令人困惑)和List是多对多的。

其次,您没有使用CoreData的固有对象图功能,而是在实体之间“滚动了自己的”关系(您应该使用界面构建器来模拟两个实体之间的CoreData关系)。

请参阅HERE如何操作。

对数据建模后,您的谓词应如下所示:

//Not tested
NSPredicate* p = [NSPredicate predicateWithFormat:@"ANY members = %@",self.currentMember];

请勿传递格式化字符串以创建谓词,使用NSPredicate格式替换参数,否则您将无法实现目标(在大多数情况下)。