我已将json数据保存在核心数据中。我的应用程序的问题是,每当我再次调用api时,被调用并保存的数据都会追加到核心数据的新行中。我想要的是每当我再次调用api时,之前的数据都将被替换或更新。我该如何实现?我阅读了它,可以使用 NSBatchUpdateRequest ,但我仍然不知道如何实现。
这是我的代码
ApiSession.shared.send(request) { (response) in
if let err = response.error {
print("Failed to get youtube data:", err)
return
}
guard let results = response.value else { return }
self.nextPageToken = results.nextPageToken
results.items.forEach({ (result) in
let context = CoreDataManager.shared.persistenceContainer.viewContext
if let video = NSEntityDescription.insertNewObject(forEntityName: "Video", into: context) as? Video {
video.videoTitle = result.snippet.title
video.videoId = result.id.videoID
}
let request: NSFetchRequest<Video> = Video.fetchRequest()
do {
try context.save()
let videos = try context.fetch(request)
DispatchQueue.main.async {
self.videos = videos
self.tableView.reloadData()
}
} catch let saveErr {
print("Failed to save video:", saveErr)
}
})
}
答案 0 :(得分:1)
尝试这样的事情:
let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "Video")
fetchRequest.predicate = NSPredicate(format: "videoId = %@", result.id.videoID)
var videoList: [NSManagedObject] = []
var video: Video
do {
videoList = try context.fetch(fetchRequest)
}
catch {
print("error executing fetch request: \(error)")
}
if videoList.count > 0 {
video = videoList[0] as! Video
} else {
video = NSEntityDescription.insertNewObject(forEntityName: "Video", into: context) as? Video
video.videoId = result.id.videoID
}
if let v = video {
v.videoTitle = result.snippet.title
}
答案 1 :(得分:1)
要更新现有记录,您必须通过给定的ID来获取它,并检查记录是否存在。
如果存在,请对其进行更新。
如果没有,请创建一个新的
ApiSession.shared.send(request) { response in
if let err = response.error {
print("Failed to get youtube data:", err)
return
}
guard let results = response.value else { return }
self.nextPageToken = results.nextPageToken
let context = CoreDataManager.shared.persistenceContainer.viewContext
results.items.forEach({ result in
let request: NSFetchRequest<Video> = Video.fetchRequest()
request.predicate = NSPredicate(format: "videoId == %@", result.id.videoID) // if videoID is Int change the placeholder to `%ld`
do {
let videos = try context.fetch(request)
if let video = videos.first {
video.videoTitle = result.snippet.title
self.videos.append(video)
} else {
let video = NSEntityDescription.insertNewObject(forEntityName: "Video", into: context) as! Video
video.videoTitle = result.snippet.title
video.videoId = result.id.videoID
}
} catch {
print("Failed to fetch video:", error)
}
})
do {
try context.save()
} catch {
print("Failed to save video:", error)
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}