Core Data simple relationship in code

為{幸葍}努か 提交于 2019-12-03 14:07:06

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/1177148/core-data-simple-relationship-in-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!