Showing a UIAlertController when there is a NSConstraintConflict
Showing a UIAlertController when there is a NSConstraintConflict
I'm inserting data into my CoreData stack (which has only one entity with a few attributes). In Xcode, I've set the attribute "patientID" to be a unique constraint.
When attempting to add a new entry, this does as expected and throws an error in Xcode's console (NSConstraintConflict
). However, in-app nothing is shown.
NSConstraintConflict
How would I go about adding a UIAlertController to state that this is a duplicate entry?
My current function for saving to CoreData is as follows:
func save(newID: String, newDOB: String, newAge: String, newGender: String, newHeight: String, newWeight: String, newRace: String, newADLS: String)
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else
return
// 1
let managedContext = appDelegate.persistentContainer.viewContext
// 2
let entity = NSEntityDescription.entity(forEntityName: "Patient", in: managedContext)!
let person = NSManagedObject(entity: entity, insertInto: managedContext)
// 3
person.setValue(newID, forKeyPath: "patientID")
person.setValue(newDOB, forKey: "dob")
person.setValue(newAge, forKey: "age")
person.setValue(newGender, forKey: "gender")
person.setValue(newHeight, forKey: "height")
person.setValue(newWeight, forKey: "weight")
person.setValue(newRace, forKey: "race")
person.setValue(newADLS, forKey: "adls")
// 4
do
try managedContext.save()
dismiss(animated: true, completion: nil)
//No need for this - this occurs appends during viewWillAppear
//ids.append(person)
catch let error as NSError
print("Could not save. (error), (error.userInfo)")
1 Answer
1
You can fetch all records before every insert and verify that the new patientID doesn't exist before the insert and if exists show the alert
after you fetch the array
if fetchedArray.map$0.patientID.contains(newID)
// show alert here as id exists
return
// proceed in saving the new record
NSFetchRequest
see edit ........
– Sh_Khan
Sep 8 '18 at 19:25
I got it to work, thank you so much!
– chumps52
Sep 8 '18 at 20:09
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Thanks, how would I go about doing this? I'm pretty much completely new to CoreData (and only a newbie at Swift in general). I know how to make a
NSFetchRequest
with a predicate, but no idea how I'd then compare that to what's been inputted by the user/show the alert etc.– chumps52
Sep 8 '18 at 19:18