ios - Handling duplicate entries in Core Data -


i have app allows users save favorites. using core data store favorites managed objects. have written code prevent possibility of storing duplicates, wondering if there better way so. each favorite object has id field unique. in following code looping through , checking id field, , if value exists, setting flag value true, , breaking out of loop.

-(bool)addfavorite{     bool entityexists = no;     if(context){         // favorite exist?         nsarray *allfaves = [appdataaccess getallfavorites];         for(favorite *f in allfaves){             if([f.stationidentifier isequaltostring:stid]){                 entityexists = yes;                 break;             }         }         if(!entityexists){             nserror *err = nil;             favorite *fave = [favorite insertinmanagedobjectcontext:context];             fave.stationrealname = rivergauge.name;             fave.stationidentifier = stid;             fave.stationstate = @"wv";             if(![context save:&err]){                 nslog(@"error: not save context--%@", err);             }             return yes;                     }     return no; } 

i wondering if core data has ability check see if object being added duplicate. there predicate can handle checking duplicates? thanks!

coredata no uniquing itself. has no notion of 2 entries being identical.

to enable such behavior have implement doing 'search before insert' aka 'fetch before create'.

nsfetchrequest *fetch = [nsfetchrequest fetchrequestwithentityname:@"favorite"]; nspredicate *predicate = [nspredicate predicatewithformat:@"stationidentifier == %@", stid]; [fetch setpredicate:predicate]; yourobject *obj = [ctx executerequest:fetch];  if(!obj) {     //not there create , save     obj = [ctx insertnewmanagedobjectforentity:@"favorite"]; //typed inline, dont know actual method     obj.stationidentifier = stid;     [ctx save]; }  //use obj... e.g. nslog(@"%@", obj.stationidentifier); 

remember assumes single-threaded access


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -