Core Data Simple Relationships in Code

I am new to cocoa trying to build an iPhone app, including Core Data.

My problem is this: I have a small application that is currently working with one object, called a playlist, which I show in a table, and can add or remove entries.

I have this in my PlayerAppDelegate:

playlistManagedObjectModel

playlistListManagedObjectContext

playlistListPersistentStoreCoordinator

Adding an object with:

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

Now I want to add a sublayer called Song with a to-many relationship.

Added playlist attribute: songRelation Added song attribute: playlistRelation

I created this object and established relationships in both directions by clicking the Optional checkbox because I want to have at least one song in the playlist.

After setting this relationship, I can now no longer create a playlist without warning. The problem is that โ€œheโ€ wants to create a Song, but I donโ€™t know how to do it.

I cannot find one place with an example of how to add a new playlist in this case, i.e. when there is a relation to another object to be added.

Do I need to create them:

 songManagedObjectModel songListManagedObjectContext songListPersistentStoreCoordinator 

or is a Song entity accessible through a playlist object in some way?

Something like this is possible:

Add playlist

Add song

Set the attributes of the relationship (how?)

Save to Permanent Storage

Or????

I really have a lot of googled and probably misunderstood something basic here, as there are no examples available ....

Rgds PM

+3
source share
1 answer

Petter

There should be a method in the PlayList model object that looks something like this:

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

This is a dynamically generated method that inserts a Song value into the ratio for songs in a PlayList. If you have not generated a PlayList model object since you added the Song relationship, this method will not be there. Thus, make sure that you create model classes for any modified objects.

The Song object that you pass to the addSongObject method must be created using ManagedObjectContext, for example:

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

Jack

+7
source

Source: https://habr.com/ru/post/1432209/


All Articles