Im my iPhone project, I have a data model with 2 objects: Profile and Contact. They are related to each other, with 1 Profile having many Contacts. Here is what I’m not sure about:
What is the right way to assign a Profile to a Contact when I add the Contact to the database?
I know how to add the contact to the database, but I need to know the right way to add the profile.
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];
Do I need to fetch the Profile first? Do I use a separate managedObjectContext, or the same one?
I have the first name of the profile, which I know I can use to fetch it like this:
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];
I think I could do it like this, but if somebody could give me a code block with the best practice, that would be great. Thanks!
You fetch the profile first, you can use the same MOC. Then just assign it to the profile property on the Contact.
[NSEntityDescription entityForName:@"Profile" inManagedObjectContext:self.moc]is not returning a Profile object though. It returns an entity description.+ (NSEntityDescription *)entityForName:(NSString *)entityName inManagedObjectContext:(NSManagedObjectContext *)contextYou need to use a fetch request on the MOC. Checkout this:
http://cocoawithlove.com/2008/03/core-data-one-line-fetch.html