gpt4 book ai didi

ios - Swift 中的核心数据 : Only saving last object in a for loop

转载 作者:行者123 更新时间:2023-11-30 12:36:41 25 4
gpt4 key购买 nike

我尝试在 for 循环中将 Core Data 中的多个对象保存到 IPOdSongs 实体中,即当前在 for Song in result{} 中的歌曲标题循环。但我的代码只保存循环中的最后一首歌曲,并且只是不断覆盖同一个对象。我需要每次创建一个新对象,而不是覆盖同一个对象。我做错了什么?

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)

}
}

最佳答案

您不需要创建请求来将新对象保存到核心数据。您做错的是创建一个托管对象,插入它,然后通过循环更改它,而不是为每首歌曲创建一个新对象。

这应该有效:

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 returned while saving")} 放在最后。

关于ios - Swift 中的核心数据 : Only saving last object in a for loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42773539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com