问题描述
我正在尝试在 for
循环中将 Core Data 中的多个对象保存到 iPodSongs 实体,即当前在 for song in result 中的歌曲标题{}代码>循环.但是我的代码只保存循环中的最后一首歌曲,并且只是不断覆盖同一个对象.每次我都需要创建一个新对象,而不是覆盖同一个对象.我做错了什么?
I'm trying to save multiple objects in Core Data to the IPodSongs entity in a for
loop, namely the title of the song currently in the for song in result{}
loop. But my code only saves the very last song in the loop, and just keeps overwriting the same object. Instead of overwriting the same object, I need to create a new object each time. What am I doing wrong?
func fetchiPodSongsOnSignup() {
var appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var context: NSManagedObjectContext = appDel.managedObjectContext!
var newSong = NSEntityDescription.insertNewObjectForEntityForName("IPodSongs", inManagedObjectContext: context) as! NSManagedObject
var request = NSFetchRequest(entityName: "IPodSongs")
request.returnsObjectsAsFaults = false
var results = context.executeFetchRequest(request, error: nil)
let query = MPMediaQuery.songsQuery()
let result = query.collections as! [MPMediaItemCollection]
for song in result {
for song in song.items as! [MPMediaItem] {
newSong.setValue("(song.valueForProperty(MPMediaItemPropertyTitle))", forKey: "title")
println(newSong)
context.save(nil)
}
}
推荐答案
您无需创建将新对象保存到 Core Data 的请求.你做错的是创建一个单一的托管对象,插入它,然后通过循环更改它,而不是为每首歌曲创建一个新对象.
You dont need to create a request to save new objects to Core Data. What you did wrong was create a single managed object, inserted it and then changeded it through the loop instead of creating a new object for each song.
这应该有效:
func fetchiPodSongsOnSignup() {
var appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var context: NSManagedObjectContext = appDel.managedObjectContext!
let query = MPMediaQuery.songsQuery()
let result = query.collections as! [MPMediaItemCollection]
for song in result {
for song in song.items as! [MPMediaItem] {
var newSong = NSEntityDescription.insertNewObjectForEntityForName("IPodSongs", inManagedObjectContext: context) as NSManagedObject
newSong.setValue("(song.valueForProperty(MPMediaItemPropertyTitle))", forKey: "title")
println(newSong)
}
}
if context.save(&errorPointer == false {
printlin("Error received while saving")
}
}
同时把 if context.save(&errorPointer == false {printlin("Error received while Saving")}
放在最后.
这篇关于Swift 中的核心数据:只在 for 循环中保存最后一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!