Handling duplicate entries in Core Data

前端 未结 6 507
野的像风
野的像风 2021-02-04 10:28

I have an app that allows users to save favorites. I am using Core Data to store the favorites as managed objects. I have written some code to prevent the possibility of storing

6条回答
  •  暖寄归人
    2021-02-04 10:42

    CoreData does no uniquing by itself. It has no notion of two entries being identical.

    To enable such a behavior you have to implement it yourself by doing a 'search before insert' aka a '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 so create it and save
        obj = [ctx insertNewManagedObjectForEntity:@"Favorite"]; //typed inline, dont know actual method
        obj.stationIdentifier = stID;
        [ctx save];
    }
    
    //use obj... e.g.
    NSLog(@"%@", obj.stationIdentifier);
    

    Remember this assumes single-threaded access

提交回复
热议问题