ios - 将字典保存到核心数据

标签 ios core-data swift

我的应用程序解析播客 RSS 提要。我使用 2 个实体:播客(用于保存播客相关数据)和剧集(剧集数据,如摘要等)。解析提要后,我将剧集列表存储在名为“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)")
    }
}

请问有什么想法吗?

最佳答案

该错误表明您的数组不包含 NSDictionary 对象 - 这就是为什么当您尝试访问元素 作为 时会出现动态强制转换异常的原因NSDictionary.

从您的评论来看,您的数组似乎实际上包含 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

    }

关于ios - 将字典保存到核心数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27749298/

相关文章:

ios - 更新期间iOS App的生命周期

ios - 如何使用 Core Data 访问和使用实体

iphone - 如何使用 NSOrderedSet 的顺序对 NSFetchedResultsController 的结果进行排序

ios - Swift FFT - 复杂的拆分问题

ios - 正确使用转场

ios - 如何验证 Sign In With Apple 中的 realUserStatus 值

ios - 如何知道我之前在 iOS 中的标签栏 View Controller 是哪个?

ios - 排序核心数据获取(swift 4)

swift - 如何对强制展开进行单元测试

swift - 如何在 Swift 和 SpriteKit 中添加涟漪效果