Reputation: 1723
I have a core data in one of my application.All the data are populated from server.At a point i have to check whether the data from the server is already existing in the core data or not.If it is already existing,just have to replace it.The checking can be done with a unique value that i have for each entry.How can i achieve this? This is what i have done:
` for(int i=0;i<[ar count];i++){
NSFetchRequest * request = [[NSFetchRequest alloc] init];
NSManagedObjectContext *context=[Server serverInfo].context;
[request setEntity:[NSEntityDescription entityForName:@"Coupon" inManagedObjectContext:context]];
[request setPredicate:[NSPredicate predicateWithFormat:@"upc_code = %@",[ [ar objectAtIndex:i]objectForKey:@"upc_code"]]];
NSUInteger count = [context countForFetchRequest:request error:nil];
[request release];
// [context ]
if (count > 0){
NSLog(@"found");}'
Here ar is the array fetching from the server.The context is the user can sometimes make edits in the entries from the server.I need all the data in the server synced with the device.
Upvotes: 0
Views: 169
Reputation: 2083
Don't do a countForFetchRequest
, in stead do executeFetchRequest:error:
which will return an array with results. This array should have 0 or 1 results, more than 1 would be inconsistent since I assume that your upc_code
is unique.
If you have 0 results, create a new object in your context and set its properties
If you have 1 result, just update your properties of that object that was returned by executeFetchRequest:error:
And finally save your context and your done
Upvotes: 1