Search code examples
iosswiftcore-datansmanagedobjectcontextnsmanagedobjectid

Swift, CoreData and many-to-many-relationship: how to access order of subitems?


I've the following relationship:

Playlist may have one-to-many songs, and Song may belong to one-to-many playlists.

My problem consists in getting the order of a song in a specific playlist - for example,

  • in Playlist 1, the order maybe 3,
  • in Playlist 2, the order maybe 1,
  • in Playlist 3, the order maybe 5, etc.

In addition, the order of the songs within a playlist can be changed as they are listed in a tableview.

I now want to keep track of the orders.

I've tried the following approaches:

  1. Creating an new attribute "PlaylistOrders" for the Song entity - working with a NSSet which represents the orders (order and ManagedObjectId of the Playlist),
  2. Creating a new Entity named "PlaylistOrders" and wiring it to "Song". Also this new entity contains an objectId (ManagedObjectId) as Transformable.

Both approaches seem to be very error-prone - in addition I constantly get a warning such as "'NSKeyedUnarchiveFromData' should not be used to for un-archiving and will be removed in a future release".

Is there a better and more sophisticated approach storing and retrieving a Song's order within different playlists?


Solution

  • In the properties of your songs relationship in the Playlist entity in the Data Model, tick the "Ordered" checkbox. Instead of NSSet, they will be available as NSOrderedSet then.