我想将保存在核心数据中的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()
}
}
答案 0 :(得分:1)
尝试一下并查看结果:
private var videos = [Video]() {
didSet {
print("AAA: \(videos.last().title)")
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
}
确保已将numberOfItems和Section设置为array.count