The user is able to select audio files that they want to add to their playlist. Their audio file library may contain 1000 to 100000 songs.
Since the user can select a lot of songs to be added to their playlist, whenever they tap on a list row for an audio file, it would create a new song object and saves the managed object context to the persistent store of Core Data to avoid using too much memory as some have suggested in my previous questions.
But doing so means, I can’t use rollback() method of NSManagedObjectContext since the song has been saved to the persistent store.
So is there a way to rollback changes made in the persistent store?
Have attached a full working example:
struct PlaylistSongSelectionView: View {
let playlist: Playlist
@FetchRequest(sortDescriptors: []) var audioFiles: FetchedResults<AudioFile>
@Environment(.managedObjectContext) var moc
var body: some View {
List {
ForEach(audioFiles) { audioFile in
Button {
addSongToPlaylist(audioFile: audioFile)
} label: {
VStack {
Text(audioFile.wrappedName)
Text(audioFile.wrappedArtist)
}
}
}
}
}
func addSongToPlaylist(audioFile: AudioFile) {
let song = Song(moc: moc)
song.name = audioFile.wrappedName
song.artist = audioFile.wrappedArtist
song.playlist = playlist
try? moc.save()
}
}