ios - Check if core data attributes, contains value before adding new one -
i'd check whether category name i'm create exists or not, in core data store.
if, exists, should display alert view , not create it. if doesn't exist, can carry on creation of new category.
func createcategory() { let entity = nsentitydescription.entityforname("category", inmanagedobjectcontext: context!) let categoryentity = category(entity: entity!, insertintomanagedobjectcontext: context) let index = pickerview.selectedrowincomponent(0) let color = categorycolor[index] let fetchrequest = nsfetchrequest(entityname: "category") fetchrequest.fetchlimit = 1 let predicate = nspredicate(format: "name = %@", name.text) let fetchresults = context!.executefetchrequest(fetchrequest, error: &error) as? [category] if let results = fetchresults { var requiredcategory : category if (results.count > 0) { requiredcategory = results[0] category } else { requiredcategory = category(entity: categoryentity, insertintomanagedobjectcontext: context!) requiredcategory.name = name.text // set other properties category necessary } category?.name = requiredcategory category!.descript = descriptionfield.text category!.color = color println(category!.name) context?.save(nil) name.text = "" descriptionfield.text = "" } }
you should create fetchrequest
, execute before create categoryentity
. then, check results.count
. if count > 0
have 1 , should display alert. if isn't can create categoryentity
, configure , save it.
note may want use =[cd]
in predicate avoid multiple categories same name different capitalisation.
Comments
Post a Comment