首页 > 解决方案 > 将核心数据对象附加到数组中

问题描述

我想将我保存在核心数据中的 json 对象附加到一个数组中,但它不适用于 append。我如何将核心数据对象附加到数组中。

这是我的数组

private var videos = [Video]()

这是我获取 api 并将 json 存储到核心数据中的函数

let params = ["part": "snippet", "q": "tausiyah \(name)", "key": "AIzaSyC2mn0PTL8JmSWEthvksdJLvsnwo5Tu9BA"]

        APIServices.shared.fetchData(url: APIServices.youtubeBaseURL, params: params, of: Item.self) { (items) in
            items.forEach({ (item) in
                print(item.id.videoId)
                let privateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
                privateContext.parent = CoreDataManager.shared.persistenceContainer.viewContext

                let video = Video(context: privateContext)
                video.title = item.snippet.title
                video.videoId = item.id.videoId

                do {
                    try privateContext.save()
                    try privateContext.parent?.save()
                    self.videos.append(video) // this is I can't append core data into my array
                } catch let saveErr {
                    print("Failed to save json data:", saveErr)
                }
            })
            DispatchQueue.main.async {
                self.collectionView.reloadData()
            }
        }

标签: iosarraysswiftcore-data

解决方案


试试这个,看看结果:

private var videos = [Video]() {
   didSet {
      print("AAA: \(videos.last().title)")
      DispatchQueue.main.async {
          self.collectionView.reloadData()
      }
   }
}

确保您已将 numberOfItems & Section 设置为您的 array.count


推荐阅读