我正在使用核心数据模型来存储数据。我可以以编程方式添加数据,但删除特定行对我来说是个问题。
歌曲型号:
在 viewDidLoad 中添加新数据
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
//add a new data
let newSong = NSEntityDescription.insertNewObject(forEntityName: "Song", into: context)
newSong.setValue("turk_milleti_demokrattir", forKey: "path")
newSong.setValue("song1", forKey: "name")
do{
try context.save()
print("success")
}
catch {
print(error)
}
添加新行没问题。我想从核心数据模型中删除特定行。例如,假设我想删除名为song1的歌曲。如何删除song1?
如果是 SQL,从数据库中删除一行将是这样的:
DELETE FROM Song WHERE name='song1';
在核心数据 - Swift 3 中,我是新手。如何删除特定行?在Swift 3 - Core Data 中,什么相当于SQL 中的DELETE - WHERE语句?
我希望你在你的项目中自动创建了你的模型类,如果这有帮助,请检查以下代码
let fetchRequest: NSFetchRequest<Song> = Song.fetchRequest()
fetchRequest.predicate=NSPredicate(format: "name = %@", "song1")
var fetchedItems = [Song]()
do{
fetchedItems=try context.fetch(fetchRequest)
}catch{
fatalError("Could not fetch")
}
for item in fetchedItems{
context.delete(item)
}
context.save()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句