Reputation: 1569
I'm working on a Core Data based application (I'm used to work with sqlite, but this time I wanted to learn something new) and I'm stuck on this relation problem:
I have Songs and Playlists, and I want to relate them with an order number, so playlists can be like this:
- "Playlist A"
1. Song A
2. Song C
3. Song B
- "Playlist B"
1. Song C
2. Song A
3. Song B
4. Song F
5. Song E
This is an obvious many-2-many case, with (i know it's not standard) the order number stored in related table; in sql I'd do
Table "Songs" (id, name, ecc..)
Table "Playlists" (id,name, ecc..)
Table "PlaylistSongs" (playlist_id,song_id,position)
In Core Data i did:
Entity "Song"
Entity "Playlist"
Entity "SongInPlaylist"
with this relation:
Song <---->> SongInPlaylist
Playlist <----->> SongInPlaylist
But now i don't know how to:
a) put a song in playlist at certain index b) get songs in a playlist in correct order c) modify playlist order.
Does anybody can help me?
Upvotes: 2
Views: 754
Reputation: 28409
It seems this is an ideal use for ordered relationships. Simply check the "Ordered" box in the data model editor, and each play list will hold references to its songs in the order you prescribe.
Upvotes: 0
Reputation: 1118
Song *song = yourSong;
Playlist *playlist = yourPlaylist;
NSNumber *position = songsPositionInPlaylist;
// add song to playlist
SongInPlaylist *sip = [NSEntityDescription insertNewObjectForEntityForName:@"SongInPlaylist" inManagedObjectContext:yourContext];
sip.song = yourSong;
sip.playlist = yourPlaylist;
sip.position = songsPositionInPlaylist;
[yourContext save:nil];
Upvotes: 1
Reputation: 31016
It seems that a SongInPlaylist needs a position
attribute. You can then give the PlayList some methods to insert at an index, move from one index to another, or remove at an index which would fix the position values of other SongInPlaylist entities.
Upvotes: 1
Reputation: 1754
Add an item in the middle, something like "PlaylistEntry", that points to a Song and has a field for order. Build your play lists out of PlaylistEntries rather than Songs directly. You can then sort on the order field and manipulate it to change the sorting of the Playlist.
Upvotes: 0