ios - Core Data - Insert based by parameter -
i have table called person. how make data entry based name, not repeat names.
example:
i have person named josh. can not have person named josh.
similar function of pk.
unfortunately, coredata doesn't have built-in way prevent dupes.
first, fetch request predicate see if value exists. if not exist, insert new entity.
example)
let appdelegate = uiapplication.sharedapplication().delegate appdelegate let managedcontext = appdelegate.managedobjectcontext! let personname = "josh" let fetchrequest = nsfetchrequest(entityname: "person") let predicate = nspredicate(format: "name = %@", personname) fetchrequest.predicate = predicate var error: nserror? let fetchedresults = managedcontext.executefetchrequest(fetchrequest, error: &error) [nsmanagedobject]? if let results = fetchedresults { // if no results found, insert if results.count == 0 { let entity = nsentitydescription.entityforname("person", inmanagedobjectcontext: managedcontext) let person = person(entity: entity!, insertintomanagedobjectcontext:managedcontext) person.setvalue(personname, forkey: "name") var error: nserror? if !managedcontext.save(&error) { println("could not save \(error), \(error?.userinfo)") } } } else { println("could not fetch \(error), \(error!.userinfo)") }
Comments
Post a Comment