Core Data fetching data and looking for duplicate

I want to fetch data from Core data and look for duplicats and then only save the data then there is no duplicate of the movieid. Maybe some one can help me ..

How can I compare the result with the movieid string ?

let request = NSFetchRequest<NSFetchRequestResult>(entityName: "MovieData")
        //request.predicate = NSPredicate(format: "movieid = %@", movieID)
        request.returnsObjectsAsFaults = false
        do {
            let result = try context.fetch(request)
            for data in result as! [NSManagedObject] {
               print(data.value(forKey: "movieid") as! String)
          }

        } catch {

            print("Failed")
        }

Upvotes: 0

Views: 259

Answers (3)

vadian
vadian

Reputation: 285064

Almost. Apply the predicate to get only the record with the specific movieID. However it assumes that movieID is an object (NSNumber), if it's an scalar Int you have to use %ld as placeholder.

If the fetch returns an empty array there is no duplicate and you can insert a new object

let request = NSFetchRequest<NSManagedObject>(entityName: "MovieData")
request.predicate = NSPredicate(format: "movieid = %@", movieID)
do {
    let result = try context.fetch(request)
    if result.isEmpty {
        let newMovie = NSEntityDescription.insertNewObject(forEntityName: "MovieData", into: context) as! MovieData
        newMovie.movieid = movieID
        try context.save()
    }      
} catch {
    print(error)
}

Upvotes: 1

Joakim Danielson
Joakim Danielson

Reputation: 51945

Create a cache for movieid values to check for duplicates and loop through the fetched result and delete any objects with a movieid already in the cache and then save once the loop is done.

var selection: [String] = []
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "MovieData")

request.returnsObjectsAsFaults = false
do {
    let result = try context.fetch(request)
    for data in result as! [NSManagedObject] {
        guard let movieId = data.value(forKey: "movieid") as? String else {
            context.delete(data) // or however you want to handle this situation
            continue
        }
        if selection.contains(movieId) {
            context.delete(data)
        } else {
            selection.append(movieId)
        }
    }
    try context.save()
} catch {
    print("Failed")
}

Upvotes: 0

Shemona Puri
Shemona Puri

Reputation: 811

While saving in core data you need to create predicate and in there you need to check if there are values already saved with same "movieid" then it has to be updated , this way you won't have duplicate data . Please refer the method and try using the same for saving the values in DB . This way duplicate values won't be saved in DB

class func insertupdaterecord (movieID:String, context: NSManagedObjectContext)
{
    let entityDescription = NSEntityDescription.entity(forEntityName: "movie", in: context)
    let pred = NSPredicate(format: "movieid = %@", movieID)

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "movie")
    fetchRequest.entity    = entityDescription
    fetchRequest.predicate = pred

    let result = try! (context.fetch(fetchRequest) as NSArray).lastObject
    let updateInsertInfo : movie

    if result != nil
    {
        updateInsertInfo               = result as! movie
    }
    else
    {
        print("Record not found!")
    }
    do
    {
        try context.save()
    }
    catch let error as NSError
    {
        print("Error while saving \(error) in database.")
    }
}

Upvotes: 0

Related Questions