我看了一遍,但我找不到这个问题的答案。
我正在将播客及其相关剧集保存到Parse,但以下代码仅保存1集和播客(我想在for循环中找到的每个条目都会重置currentP
并且只保存找到的最后一个值) 。
let currentP = PFObject(className: self.podcastClass)
currentP["user"] = PFUser.currentUser()
currentP["name"] = name
currentP["artist"] = artist
currentP["summary"] = summary
currentP["feedURL"] = feedURL
currentP["artworkURL"] = artworkURL
currentP["artwork"] = artwork
currentP["date"] = date
let episodesToParse = PFObject(className: self.episodesClass)
for episode in episodes {
episodesToParse["showDate"] = episode.date
episodesToParse["title"] = episode.title
episodesToParse["downloadURL"] = episode.enclosures[0].valueForKey("url") as? String
episodesToParse["showNotes"] = episode.summary
episodesToParse["localPath"] = ""
episodesToParse["isDownloaded"] = "no"
episodesToParse["parent"] = currentP
}
episodesToParse.saveInBackground()
如果我使用episodesToParse.addObject(episode.date, forKey: "showDate")
之类的内容,则会返回以下错误:
[Error]: invalid type for key showDate, expected date, but got array (Code: 111, Version: 1.8.1)
我不知道该怎么办。我想要的是currentP被保存,它的所有剧集都保存在与其父级(Podcast)有关系的不同类中。如果你一次添加一集而不是一大堆(我希望能够一次保存500个episodesToParse
个实例,我发现了很多方法可以做到这一点。
感谢您的帮助。
答案 0 :(得分:2)
问题是,你在循环后保存episodesToParse
。您必须在循环内移动episodesToParse.saveInBackground()
,以便每次循环设置剧集的属性时剧集都会更新:
for episode in episodes {
episodesToParse["showDate"] = episode.date
episodesToParse["title"] = episode.title
episodesToParse["downloadURL"] = episode.enclosures[0].valueForKey("url") as? String
episodesToParse["showNotes"] = episode.summary
episodesToParse["localPath"] = ""
episodesToParse["isDownloaded"] = "no"
episodesToParse["parent"] = currentP
//Inside
episodesToParse.saveInBackground()
}
或者您可以使用PFObject.saveAllInBackground
保存所有对象:
var episodesToSave[PFObject] = []
for episode in episodes {
var episodeToParse
episodeToParse["showDate"] = episode.date
episodeToParse["title"] = episode.title
episodeToParse["downloadURL"] = episode.enclosures[0].valueForKey("url") as? String
episodeToParse["showNotes"] = episode.summary
episodeToParse["localPath"] = ""
episodeToParse["isDownloaded"] = "no"
episodeToParse["parent"] = currentP
//Add to episode-array
episodesToSave.append(episodesToParse)
}
//Save all objects in the array
PFObject.saveAllInBackground(episodesToSave)