我正在Swift的一个项目中工作,我将一组记录保存到核心数据,这很好。我保存它的方式如下。
public static func savePlaylistDetails(audio: [(title: String, healerName: String, trackUrl: String, trackID: String, imageUrl: String)] = [], playListName: String) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let newPlaylist = NSEntityDescription.insertNewObject(forEntityName: PlayList_DETAILS_ENTITY, into: context)
let track = audio.map{ $0.trackID }
print("Track",track)
let trackId = track[0]
print("ID is :", trackId)
newPlaylist.setValue(playListName, forKey:"playlistName")
newPlaylist.setValue(trackId, forKey:"trackID")
do{
try context.save()
print("Saved.....")
} catch{
print("There was an error")
}
}
如您所见,单个playList可能有多个轨道ID,这与上面的代码一起工作正常。但是我的要求是在更改实体名称或轨道ID后更新记录。我尝试按下面的顺序,但值重复。例如,如果我想在同一个播放列表中放置一组新曲目,并且如果我删除现有曲目,则会变得一团糟。
点击更新按钮时:
for item in selectedSongArray {
let trackID = item.trackID
print("Trck Id :",trackID)
updateAnItemFromCoreData(playListName: playListName, trackId: trackID)
}
selectedSongArray
包含我要保存的值。 update
方法如下。
public static func updatePlaylistDetails(playlistName: String, trackID: String) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: PlayList_DETAILS_ENTITY)
request.predicate = NSPredicate(format: "playlistName = %@", playlistName)
do {
let results = try context.fetch(request)
request.returnsObjectsAsFaults = false
print("Results Count :", results.count)
if(results.count > 0 ){
for result in results as! [NSManagedObject] {
result.setValue(playlistName, forKey: "playlistName")
result.setValue(trackID, forKey: "trackID")
try context.save();
print("Saved.....")
}
} else {
print("No Audios to save")
}
} catch{
print("There was an error")
}
}