Reputation: 6570
How to do if exists update else insert
in Core Data?
Do I need to program it step by step or there is actually an API for this?
Upvotes: 2
Views: 2980
Reputation: 618
here is my code in objective c, you can use NSPredicate to check the item already exist,
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Trend_news_table" inManagedObjectContext:managedObjectContext]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"news_id = %@",[user_info objectForKey:@"news_id"]]];
[request setPredicate:predicate];
NSError *error = nil;
NSArray *results = [managedObjectContext executeFetchRequest:request error:&error];
if (results.count > 0)
{
NSLog(@"update");
}
else
{
NSLog(@"Insert");
}
Upvotes: 4