There’s is a severe lack in documentation regarding heavyweight migration and apple docs is extremely lacklustre.
My old model used to have playlists and songs where they have a one to many relationship where one playlist contains many songs. The songs are ordered for each playlist thus was using an NSOrderedSet
In the new model, I want to remove this relationship, and go over song in a playlist and add the playlist UUID to the new “playlistId” attribute of each song.
Furthermore, since I want to retain the order of the songs were in in their respective playlists, each song will be assigned an index of 0 onwards so I can use a sort descriptor to sort the songs for a playlist.
I hope I am clear with my intention here.
class PlaylistSongMappingModel: NSEntityMigrationPolicy {
override func createDestinationInstances(forSource sInstance: NSManagedObject, in mapping: NSEntityMapping, manager: NSMigrationManager) throws {
if sInstance.entity.name == "Playlist" {
//Nothing is printed out...
let songs = sInstance.mutableOrderedSetValue(forKeyPath: "songs")
print(songs.array as? [Song])
}
}
}
extension Playlist {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Playlist> {
return NSFetchRequest<Playlist>(entityName: "Playlist")
}
@NSManaged public var name: String?
@NSManaged public var id: UUID?
}
extension Song {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Song> {
return NSFetchRequest<Song>(entityName: "Song")
}
@NSManaged public var name: String?
@NSManaged public var fileExtension: String?
@NSManaged public var artist: String?
@NSManaged public var index: Int64 //New attribute: The index at which the this song is in a playlist
@NSManaged public var playlistId: UUID? //New attribute: The playlist the song is associated with.
var wrappedName: String {
name ?? "Unknown Song"
}
var wrappedFileExtension: String {
fileExtension ?? "Unknown File Extension"
}
var wrappedArtist: String {
artist ?? "Unknown Artist"
}
var wrappedPlaylistId: UUID {
playlistId ?? UUID()
}
}