开发者

Checking for duplicate in sqlite before inserting them (Core data)

i'm inserting new objects into the database by core data. Is there any way to check if there is any duplicate in the database before i insert the values in?

for (int i =0;i<[categoryArray count];i++)
    {
        Category * cat = [categoryArray objectAtIndex:i];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"ICategory" inManagedObjectContext:managedObjectContext];
        NSFetchRequest *request = [[NSFetchRequest alloc] init];
        [request setEntity:entity]; 


        ICategory *catt = (ICategory *)[NSEntityDescription insertNewObjectForEntityForName:@"ICategory" inManagedObjectContext:managedObjectContext];
        [catt setName:cat.name];
        [catt setID:cat.ID];
        [catt setPhoto:cat.photo];
        [catt setSapphireID:event.ID];
        NSLog(@"cattttt have %@", catt);
    }

everytime i run the app , it reinsert the values again. i want to check if there is any new category in it if there isnt开发者_StackOverflow then i will add that new one in only.


There is no way to check for duplicates for free. You need to manually handle the predicate you use for determining that two objects are the same.

Easiest is to use -[NSMangedObjectContext countForFetchRequest:error:] quickly see if the object already exists, as in the count is greater than 0.

Following the rule of three (make it general the third time you need to rewrite it) I have made some convenience methods for myself to handle this. More specifically -[NSManagedObjectContext insertNewUniqueObjectForEntityForName:withPredicate:]. It's available as open source at https://github.com/jayway/CWCoreData if you want to use it as inspiration, or as-is.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜