Petter Magnusson
Petter Magnusson

Reputation: 309

Core Data simple relationship in code

I am a cocoa newbie trying to create an iPhone app including Core Data.

My problem is this: I have a little app running now with a single entity called Playlist that I display in a table view and can add and delete entries in.

I have these in my PlayerAppDelegate:

playlistManagedObjectModel

playlistListManagedObjectContext

playlistListPersistentStoreCoordinator

Adding entity with:

Playlist *playlist = (Playlist *)[NSEntityDescription
    insertNewObjectForEntityForName:@"Playlist" 
             inManagedObjectContext:playlistListManagedObjectContext];

Now I want to add a sublevel called Song with a to-many relation.

Playlist attribute added: songRelation Song attribute added: playlistRelation

I have created this entity and set up the relations both ways, clicking of the Optional flag as I want to have at least one Song in a Playlist.

After setting this relation I can now no longer create a Playlist without getting a warning. The problem is that "it" wants a Song created too, but I dont know how.

I cant find a single place with an example on how to add a new playlist in this case, ie when is has a relation to another entity that has to be added too.

Do I need to create these:

songManagedObjectModel
songListManagedObjectContext
songListPersistentStoreCoordinator

or is the Song entity accessible via the playlist entity somehow?

Something like this perhaps:

Add Playlist

Add Song

Set up "relation" attributes (how?)

Save to persistent store

Or????

I have really googled a lot and has probably misunderstood something basic here since there are no examples available....

Rgds PM

Upvotes: 3

Views: 6541

Answers (1)

Jack Cox
Jack Cox

Reputation: 3300

Petter,

There should be a method on the PlayList model object that is something like:

- (void) addSongObject:(Song *)value;

It is a dynamically generated method that will insert a Song value into the relationship for songs in PlayList. If you have not generated the PlayList model object since adding the Song relationship, that method will not be there. So, make sure you generate model classes for any changed entities.

The Song object that you pass to the addSongObject method should be created using the ManagedObjectContext like:

Song *song = (Song *)[NSEntityDescription insertNewObjectForEntityForName:@"Song" inManagedObjectContext:playlistListManagedObjectContext];

Jack

Upvotes: 7

Related Questions