在我的 iPhone 项目中,我有一个包含 2 个对象的数据模型:个人资料和联系人。它们相互关联,1 个配置文件有多个联系人。以下是我不确定的内容:
当我将联系人添加到数据库时,将配置文件分配给联系人的正确方法是什么?
我知道如何将联系人添加到数据库中,但我需要知道添加个人资料的正确方法。
self.moc = [((AppDelegate *)[[UIApplication sharedApplication] delegate]) managedObjectContext];
Contact *contact = [NSEntityDescription insertNewObjectForEntityForName:@"Contact" inManagedObjectContext:self.moc];
contact.recordID = recID;
contact.profile = ????????
NSError *err = nil;
[self.moc save:&err];
我需要先获取配置文件吗?我是使用单独的 managedObjectContext,还是使用同一个?
我有个人资料的名字,我知道我可以用它来获取它:
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
self.moc = [appDelegate managedObjectContext];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(firstName like %@)", appDelegate.currentProfile];
Profile *fetchedData = (Profile *)[NSEntityDescription entityForName:@"Profile" inManagedObjectContext:self.moc];
我想我可以这样做,但如果有人能给我一个包含最佳实践的代码块,那就太好了。谢谢!
最佳答案
您首先获取配置文件,您可以使用相同的 MOC。然后只需将其分配给联系人的配置文件属性即可。
[NSEntityDescription entityForName:@"Profile"inManagedObjectContext:self.moc]
没有返回 Profile 对象。它返回一个实体描述。
+ (NSEntityDescription *)entityForName:(NSString *)entityName inManagedObjectContext:(NSManagedObjectContext *)context
您需要在 MOC 上使用提取请求。检查这个:
http://cocoawithlove.com/2008/03/core-data-one-line-fetch.html
关于iphone - 如何在 Core Data 中分配相关对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7855681/