user1007895
user1007895

Reputation: 3965

How do I assign a related object in Core Data?

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!

Upvotes: 1

Views: 155

Answers (1)

logancautrell
logancautrell

Reputation: 8772

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 *)context

You need to use a fetch request on the MOC. Checkout this:

http://cocoawithlove.com/2008/03/core-data-one-line-fetch.html

Upvotes: 1

Related Questions