I have a Song entity in Core data and each of them has an index attribute of type integer. I am expecting a large number of song entities and want to maintain order.
The issue is if a user adds a new song entity in the middle of the ordered array, I have to update the indices of all subsequent entities which is very slow using fetch request and then updating.
Is it advisable to use an index attribute of type double instead so I could just assign an index that is half of the previous and next items (e.g. assign an index of 1.5 for inserting a song between index 1 and 2)
extension Song {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Song> {
return NSFetchRequest<Song>(entityName: "Song")
}
convenience init(moc: NSManagedObjectContext, for unsavedSong: UnsavedSong) {
self.init(context: moc)
self.album = unsavedSong.wrappedAlbum
self.artist = unsavedSong.wrappedArtist
self.artwork = unsavedSong.wrappedArtwork
self.composer = unsavedSong.wrappedComposer
self.favourite = unsavedSong.wrappedFavourite
self.fileExtension = unsavedSong.wrappedFileExtension
self.genre = unsavedSong.wrappedGenre
self.importDate = unsavedSong.wrappedImportDate
self.name = unsavedSong.wrappedName
self.trackNumber = unsavedSong.trackNumber
self.year = unsavedSong.wrappedYear
self.playlistAddDate = unsavedSong.wrappedPlaylistAddDate
self.playlistId = unsavedSong.playlistId
self.index = unsavedSong.index
self.id = UUID() //Not sure if good idea to set the same idea from unsaved song
}
//Used to have an init that takes in an audio file when I didnt think of creating an intermediate entity to handle editing. Now Song has only talk to UnsavedSong! Not audio file or other song entities
@NSManaged public var album: String?
@NSManaged public var artist: String?
@NSManaged public var fileExtension: String?
@NSManaged public var genre: String?
@NSManaged public var id: UUID?
@NSManaged public var name: String?
@NSManaged public var playlistId: UUID?
@NSManaged public var index: Int //Used to order song entities
}