2017-08-02 123 views
1

我試圖使用核心數據保存兩種類型的數組。一個數組包含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 
} 

集合視圖應該返回數組中的縮略圖。然而,它崩潰,並帶我到應用程序委託文件。

我設置一個斷點

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

您可以添加'Content'類型的聲明嗎? –

+0

你的意思是當我在覈心數據文件中聲明它時? –

+0

@NandiinBao我添加了一張圖片 –

回答

1

您將需要符合您的內容實體的NSCoding協議。 您需要執行以下兩種方法才能做到這一點

required init?(coder aDecoder: NSCoder) { 

} 

func encodeWithCoder(aCoder: NSCoder) { 
} 
+0

你能告訴我如何做到這一點。這是我第一次使用核心數據 –

相關問題