Q:

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)
            }
        })
    }

A:

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()
    }
}

