ios - Core Data sync with JSON API -
my data model named "person" , has 3 attributes "id", "firstname", , "lastname"
when importing json data using afnetworking want able check whether entity exists or not within core data using "id" identifier. if isn't there create it, , if there merge item or update it.
right have method called duplicatecheck looks like:
nspredicate *predicate = [nspredicate predicatewithformat:@"id==%@", _person.id]; nsfetchrequest *fetch = [[nsfetchrequest alloc] init]; nserror *error = nil; [fetch setentity:[nsentitydescription entityforname:@"person" inmanagedobjectcontext:self.managedobjectcontext]]; [fetch setpredicate:predicate]; nsarray *items = [self.managedobjectcontext executefetchrequest:fetch error:&error]; (nsmanagedobject *object in items) { // not sure how check here , insert or update // save , call during api request? }
i have predicate set not sure go here. looping on each item right way go or going wrong way?
usually 1 expect identifier unique. therefor if predicate return 0 objects, know object new. if 1 returned know object exists , maybe need update it.
nsarray *items = [self.managedobjectcontext executefetchrequest:fetch error:&error]; if(items){ if([items count] == 0){ //the object not present yet. create it. } else if([items count] == 1) { nsmanageobject *obj = items[0]; //there 1 object. change properties if needed } else { //what if several objects have same identifier??? } } else { //handle error error object }
Comments
Post a Comment