我正在尝试使用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'
答案 0 :(得分:1)
You will need to conform to NSCoding protocol for your Content entity. You will need to implement following two methods to do so
required init?(coder aDecoder: NSCoder) {
}
func encodeWithCoder(aCoder: NSCoder) {
}