在我的应用中,我有两个实体Items
和Lists
,其中的项目可以属于一个列表,列表可以包含多个项目。
当我创建一个Lists
托管对象并为其分配关系时,无法通过其关系检索项目对象(我之前创建的对象)。当我在控制台中打印出来时,我得到了这个:
正如您在第一张图片中看到的那样,has_items
确实包含一个项目并打印出has_items
返回null(打印在图片的底部)。但是,当我刷新我的应用程序并尝试再次访问它时它工作正常,但现在我得到一个关系错误的东西,我知道这不是错误或错误的事情,它应该是这样。
请参阅图2,了解刷新后打印效果如何变化。
我该如何解决? (问题的重新定义:能够将对象保存到关系属性,并在保存上下文检索对象而不刷新应用程序之后)。
编辑:代码在这里
List *newList = [NSEntityDescription insertNewObjectForEntityForName:@"List" inManagedObjectContext:context];
[newList setValue:obj[@"list_name"] forKey:@"list_name"];
[newList addHas_membersObject:self.currentMember];
[newList setValue:@"NO" forKey:@"current_list"];
[newList setValue:@"YES" forKey:@"is_synced"];
[newList setValue:obj[@"objectId"] forKey:@"object_identifier"];
[context insertObject:newList];
[self saveContext:context WithCompletion:^ {NSLog(@"completion being handled");
Items *newItem = [NSEntityDescription insertNewObjectForEntityForName:@"Items" inManagedObjectContext:context];
[newItem setValue:item[@"item_detail"] forKey:@"item_detail"];
[newItem setValue:@"YES" forKey:@"is_synced"];
[newItem setValue:item.createdAt forKey:@"date_added"];
[newItem setValue:item[@"is_checked"] forKey:@"is_checked"];
[newItem setValue:newList forKey:@"belong_to_list"];
[context insertObject:newItem];
[newList addHas_itemsObject:newItem];
NSError *error;
[context save:&error];
NSLog(@"item saved");
}
答案 0 :(得分:0)
在我的代码中的某些时候,我忘了初始化应该保存对象的数组,而且我总是返回null。因此,请始终记住初始化您的阵列(我个人永远不会了解到这一点)。