Reputation: 150
When I have a CoreData entity named, say, 'Book', which has a one-to-one relationship with another entity ('Bookmark') would I need to insert both an instance of 'Book' and an instance of 'Bookmark' into a managed object context, and manually assign the relationship?
If I perform the following code to instantiate an instance of 'Book'...
Book *book = [NSEntityDescription insertNewObjectForEntityForName:@"Book" inManagedObjectContext:managedObjectContext];
Can I, or can I not, perform the following code to retrieve its bookmark without inserting an instance of 'Bookmark' into the same managed object context?
book.bookmark;
Will CoreData allocate a new instance of 'Bookmark' for me?
Before you ask me to try this and see for myself: I have. I'm either doing something wrong, or I'm meant to instantiate both instances of 'Book' and 'Bookmark' and assign the relationship manually. In my testing, the relationship has 'optional' unticked but is not attached to anything. Upon invoking the getter 'bookmark' on a 'book' instance, I receive 'nil'.
I'd like to be able to use my code above, as it will allow my controller objects to deal with the managed object context, while my model objects can ignore it entirely. From what I've read of CoreData, this seems to be the intended implementation. Please correct me if I'm wrong.
Upvotes: 3
Views: 1765
Reputation: 64428
If a Book
object always requires a Bookmark
relationship, then you can write a custom getter method for the bookmark
property that will insert a bookmark
object when needed.
Xcode will generate most to the method for you. In the data model editor control-click on the bookmark
and choose Copy Objective-C 2.0 Implementation to the clipboard
. Then tweak something like this:
- (NSManagedObject *)bookmark
{
id tmpObject;
[self willAccessValueForKey:@"bookmark"];
tmpObject = [self primitiveBookmark];
[self didAccessValueForKey:@"bookmark"];
if (tmpObject==nil){
BookmarkMO *newBookmark=[NSEntityDescription entityForName:@"Bookmark" inManagedObjectContext:self.managedObjectContext];
newBookmark.book=self; //triggers kvo relationship assignment
tmpObject=newBookmark;
}
return tmpObject;
}
Upvotes: 4
Reputation: 28248
In my experience you have to create both entities and create the relationship yourself first.
something like this should be what you need:
Bookmark *bookmark = [NSEntityDescription insertNewObjectForEntityForName:@"Bookmark" inManagedObjectContext:managedObjectContext];
[book setBookmark: bookmark];
Upvotes: 2