【问题标题】:Appending core data object into an array将核心数据对象附加到数组中
【发布时间】:2019-05-18 19:02:34
【问题描述】:

我想将我保存在核心数据中的 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()
            }
        }

【问题讨论】:

  • 获取数据将异步执行。你需要DispatchQueue.main.asyncinside获取数据闭包。
  • @Paulw11 你是什么意思?我需要再次添加调度,以便我的追加工作?
  • 抱歉,我误读了您的 }。 “不工作”和“我不能追加......”是什么意思。发生什么了?您收到错误消息吗?
  • @Paulw11 我的数组是空的,但它保存在核心数据中
  • 如果在追加后打印array.count,你会看到什么?对我来说,它仍然看起来像一个异步问题。同时显示您的numberOfItems(in section:) 代码

标签: ios arrays swift core-data


【解决方案1】:

试试这个看看结果:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多