A clear
A clear

Reputation: 27

check of the data is saved on the CoreData or not

i have a string called "word" and i stored this string into a an entity called Lose inside an attribute word, i want when the user save a string "word" again it will overwrite the current value not sitting a duplicate one, how to do that ?

what i have done so far:

        //save the data to core data
        let library = Lose(context: savecatch.context)
        library.word = "word"
        savecatch.saveContext()

before the saving i need to check if "word" is already exist or not

Upvotes: 0

Views: 653

Answers (1)

vadian
vadian

Reputation: 285079

You have to fetch the record with the given attribute, then modify it and save it

let query = "word"
let request = NSFetchRequest<Lose> = Lose.fetchRequest()
request.predicate = NSPredicate(format: "word == %@", query)
do {
   let result = try context.fetch(request)
   if let found = result.first {
       found.word = "word"
       context.save()
   }
} catch {
    print(error)
}

Upvotes: 1

Related Questions