在我的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

10-02 07:15
查看更多