将字典保存到核心数据

时间:2015-01-02 22:21:23

标签: ios core-data swift

我的应用解析播客RSS Feed。我使用2个实体:播客(用于保存播客相关数据)和剧集(剧集数据,如摘要等)。解析一个feed后,我将剧集列表存储在名为“episodesToDisplay”的数组中。当用户订阅播客时,我想将该数组中保存的数据保存在Core Data中。这是我的代码,它在下面带注释的行上抛出错误:

class Podcasts: UITableViewController {
var currentPodcast: Podcasts!

    override func viewDidLoad() {
    super.viewDidLoad()
let podcastsEntity = NSEntityDescription.entityForName("Podcasts", inManagedObjectContext: self.managedContext)
    let podcastsFetch = NSFetchRequest(entityName: "Podcasts")
    var error: NSError?

    let result = self.managedContext.executeFetchRequest(podcastsFetch, error: &error) as [Podcasts]?
    if let resu = result {
        println("res is \(resu.count)")
        self.currentPodcast = resu[0] as Podcasts
    } else {
        println("did not work")
    }
}

    @IBAction func subscribe(sender: AnyObject) {
        for dict: AnyObject in episodesToDisplay {
    let episodesEntity = NSEntityDescription.entityForName("Episodes", inManagedObjectContext: self.managedContext)
    let episodesToSave = Episodes(entity: episodesEntity!, insertIntoManagedObjectContext: self.managedContext)
    var episodes = currentPodcast.episode.mutableCopy() as NSMutableOrderedSet
    let btDict = dict as NSDictionary <---------------- Crash
        episodesToSave.title = btDict["title"] as String
        episodesToSave.summary = btDict["summary"] as String
        episodesToSave.link = btDict["link"] as String
        episodes.addObject(episodesToSave)
        currentPodcast.episode = episodes.copy() as NSOrderedSet

    }



    // Save
    var error:NSError?
    if !self.managedContext.save(&error) {
        println("could not save \(error)")
    }
}

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

该错误表示您的数组不包含NSDictionary个对象 - 这就是当您尝试访问元素asNSDictionary时获得动态强制转换异常的原因。

从您的评论看来,您的数组似乎实际上包含MWFeedItem个对象,因此您需要做的就是更改代码以使用该对象类型,然后您可以访问MWFeedItem的属性 -

@IBAction func subscribe(sender: AnyObject) {
        for item: MWFeedItem in episodesToDisplay {
    let episodesEntity = NSEntityDescription.entityForName("Episodes", inManagedObjectContext: self.managedContext)
    let episodesToSave = Episodes(entity: episodesEntity!, insertIntoManagedObjectContext: self.managedContext)
    var episodes = currentPodcast.episode.mutableCopy() as NSMutableOrderedSet
        episodesToSave.title = item.title
        episodesToSave.summary = item.summary
        episodesToSave.link = item.link
        episodes.addObject(episodesToSave)
        currentPodcast.episode = episodes.copy() as NSOrderedSet

    }