I am trying to save two types of arrays using Core Data. One array contains UIimages, and the other Array contains URL's of videos. I am able to successfully save them using this method below.
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
}
I get the Save message printed out. However while trying to load them in the collection view i get a crash.
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
}
The collection view is supposed to return as many thumbnails that are in the array. However it crashes and takes me to the app delegate file.
I set a breakpoint at
let results = try context.fetch(request)
And it goes to the breakpoint.
Then i set another breakpoint at
if results.count > 0 {
and the app crashes and takes me to the app delegate with this error:
Terminating app due to uncaught exception
'NSInvalidArgumentException',
reason: '-[Content initWithCoder:]:
unrecognized selector sent to instance 0x174a6d840'
Content?Contenttype somehow does not conform to the protocolNSCodingand the CoreData framework needs it to conform to that protocol.initWithCoder:is a method declared in theNSCodingprotocol. CoreData assumes theentityNameyou passed in conforms to it and calledinitWithCoder:upon it and then crash occurred