首页 文章

App尝试从核心数据中获取数据时崩溃

提问于
浏览
1

我正在尝试使用Core Data保存两种类型的数组 . 一个数组包含UIimages,另一个数组包含视频的URL . 我可以使用下面的方法成功保存它们 .

let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
    let newVideo = NSEntityDescription.insertNewObject(forEntityName: "Content", into: context)
    videosArray.append(session.outputURL!)
    let thumbnail = self.getThumbnail(session.outputURL!)
    thumbnails.append(thumbnail)
    newVideo.setValue(videosArray, forKey: "videos")
    newVideo.setValue(thumbnails, forKey: "thumbnails")

    do {

        try context.save()
        print("Save")

    } catch {
        print("Error")
        // Process error
    }

我打印出保存信息 . 然而,当试图在集合视图中加载它时,我遇到了崩溃 .

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext

    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Content")
    request.returnsObjectsAsFaults = false

    do {
        let results = try context.fetch(request)
        if results.count > 0 {
            for result in results as! [NSManagedObject] {
                if let fetchedThumbnails = (result).value(forKey: "thumbnails") as? Array<Any> {
                    return fetchedThumbnails.count
                }
            }
        }
    } catch {
        print("There was a crash fetching content")
    }

    return 0
}

集合视图应该返回数组中的尽可能多的缩略图 . 然而,它崩溃并带我到app委托文件 .

我设定了一个断点

let results = try context.fetch(request)

它进入了断点 .

然后我设置另一个断点

if results.count > 0 {

和应用程序崩溃并带我到应用程序委托与此错误:

Terminating app due to uncaught exception 
'NSInvalidArgumentException', 
reason: '-[Content initWithCoder:]: 
unrecognized selector sent to instance 0x174a6d840'

Image of how I Declare Entity

1 回答

  • 1

    您需要符合内容实体的NSCoding协议 . 您需要实现以下两种方法

    required init?(coder aDecoder: NSCoder) {
    
    }
    
    func encodeWithCoder(aCoder: NSCoder) {
    }
    

相关问题