1

I'm struggling to find a tutorial whereby I can update a core data entity. For example, if I have a field and an add button, I know how to add it to an entity. This field can add names: john, jack, jill but if I add john again I want to ensure that the duplicate is not entered.

Here is my add code.

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

let entity = NSEntityDescription.entity(forEntityName: "UserAccountTbl", in: context)!
let person = NSManagedObject(entity: entity, insertInto: context)

person.setValue(NameSurname, forKeyPath: "nameSurname")

try context.save()
Jawad Ali
  • 13,556
  • 3
  • 32
  • 49

1 Answers1

2

Swift 4

func isEntityAttributeExist(id: Int, entityName: String) -> Bool {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let managedContext = appDelegate.persistentContainer.viewContext
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
        fetchRequest.predicate = NSPredicate(format: "id == %@", id)

        let res = try! managedContext.fetch(fetchRequest)
        return res.count > 0 ? true : false
      }

Objective C

NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:@"UserAccountTbl"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"nameSurname == %@", ameSurname];
[fetch setPredicate:predicate];
YourObject *obj = [ctx executeRequest:fetch];

if(!obj) {
    //not there so create it and save
    obj = [ctx insertNewManagedObjectForEntity:@"UserAccountTbl"]; //typed inline, dont know actual method
    obj. nameSurname = NameSurname;
    [ctx save];
}
Jawad Ali
  • 13,556
  • 3
  • 32
  • 49