ios - 将核心数据对象附加到数组中
问题描述
我想将我保存在核心数据中的 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()
}
}
解决方案
试试这个,看看结果:
private var videos = [Video]() {
didSet {
print("AAA: \(videos.last().title)")
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
}
确保您已将 numberOfItems & Section 设置为您的 array.count
推荐阅读
- sql - SQL 无效标识符和模糊定义的别名
- android - 缺少 gradle 包来运行 Shared Preferences 应用程序
- java - BFS 或 DFS 是吃豆人女士的有效搜索算法吗
- redux - Normalizr to redux store - 多个 API 请求的最佳实践
- python - Spark 在 Scala 中打印我的 DataFrame 的形状
- c# - CefSharp vb.net 的 SetProxy
- node.js - 有没有办法在 TLS 协商期间或之后访问 HTTPS 中的 PSK 身份
- session - 服务器何时向客户端发送 CSRF 令牌?
- react-native - react-native-background-fetch,在根 index.js 中声明的函数是否需要无头背景?
- vhdl - 从 Modelsim 中的 VHDL 测试台中提取对象/信号的输出值到 .txt 文件