Handling duplicate entries in Core Data

前端 未结 6 487
野的像风
野的像风 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:32

    I was wondering if Core Data has the ability to check to see if an object being added is a duplicate.

    No, Core Data doesn't care about that.

    Is there a predicate that can handle checking for duplicates?

    Since your objects have unique IDs that you control, do a fetch for an existing favorite with that ID. Something like

    NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:@"Favorite"];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"stationIdentifier == %@", stID];
    [fetch setPredicate:predicate];
    

    If you get any results, you know that a favorite with that ID already exists. And, you have a reference to that favorite in case you want to change it.

    Your current approach is fine and probably faster if there are only a few favorites. Doing a fetch will scale better to lots of favorites.

提交回复
热议问题