Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace/update data being save in core data

I have save a json data in core data. The problem for my app is whenever I called api again, the data that being called and save is appending into new row in core data. what I want is whenever I called the api again, the data from before is being replace or update. How can I achieve this? I read it I can use NSBatchUpdateRequest but I still don't understand how to implemented.

This is my code

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)
            }
        })
    }
like image 225
ferryawijayanto Avatar asked Jul 13 '26 20:07

ferryawijayanto


2 Answers

To update an existing record you have to fetch it by given ID and check if the record exists.

If it exists, update it.
If not, create a new one.

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()
    }
}
like image 147
vadian Avatar answered Jul 15 '26 11:07

vadian


Try something like this:

    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
    }
like image 36
thomas gotzsche Avatar answered Jul 15 '26 10:07

thomas gotzsche



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!