views:

85

answers:

2

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.

+1  A: 

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];  
Slee
+1 thanks for the response. I was hoping that CoreData would handle it for me, but creating it manually is just as good. :)
Ryan
A: 

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;
}
TechZen