问题描述
我试图在Core Data中将多个对象保存到IPodSongs实体中 for
循环中,即当前在 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")
}
}
如果context.save(& errorPointer == false {printlin(保存时收到错误)}} 最后。
Also put if context.save(&errorPointer == false {printlin("Error received while saving")}
at the very end.
这篇关于Swift中的核心数据:只保存for循环中的最后一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!