I am trying to update my local database when app gets response from the web server. When app gets the update from web server, I fetch the data from the local database by matching the id with the response and get one row and perform update code but local database does not get updated and also does not give an error.
What should be the solution???
-(void)checkID:(NSMutableDictionary *)dict
{
NSDictionary *dictEvent = [dict objectForKey:@"Event"];
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *selectedManagedObject = nil;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Events" inManagedObjectContext:context];
NSSortDescriptor *sortDescObj = [[NSSortDescriptor alloc] initWithKey:@"event_id" ascending:YES];
NSError *error = nil;
NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"user_id=%@ and event_id=%@",[NSNumber numberWithInt:[[dictEvent valueForKey:@"user_id"] intValue]],[NSNumber numberWithInt:[[dictEvent valueForKey:@"id"] intValue]]]];
NSLog(@"Predicate = %@",predicate);
NSArray *arrSortDescriptors = [NSArray arrayWithObject:sortDescObj];
[fetchRequest setSortDescriptors:arrSortDescriptors];
[fetchRequest setEntity:entity];
[fetchRequest setReturnsDistinctResults:YES];
[fetchRequest setPredicate:predicate];
NSArray *arrResult = [context executeFetchRequest:fetchRequest error:&error];
if ([arrResult count]>0)
{
NSArray *arrKey = [dictEvent allKeys];
NSArray *arrValue = [dictEvent allValues];
NSLog(@"ArrKey : %@\nArrValue : %@",arrKey,arrValue);
selectedManagedObject = [arrResult objectAtIndex:0];
for(int i = 0; i < [arrKey count] ; i++)
{
NSLog(@"selectedMng :- %@",selectedManagedObject);
NSLog(@"KEY: %@\t: %@",[arrKey objectAtIndex:i],[arrValue objectAtIndex:i]);
if ([[arrKey objectAtIndex:i]isEqualToString:@"id"])
{
[selectedManagedObject setValue:[arrValue objectAtIndex:i] forKey:@"event_id"];
}
else if([[arrKey objectAtIndex:i]isEqualToString:@"invited_status"])
{
[selectedManagedObject setValue:[arrValue objectAtIndex:i] forKey:@"invite_status"];
}
else
{
[selectedManagedObject setValue:[arrValue objectAtIndex:i] forKey:[arrKey objectAtIndex:i]];
}
}
if (! [selectedManagedObject.managedObjectContext save:&error])
{
NSLog(@"updateEntityIntoDataBaseNamed - Error :: %@", [error localizedDescription]);
}
// }
}
}
Besides modifying your predicate as suggested by @Martin
note that in two cases, you are updating your object using non matching keys: this happens for id and event_id, and for invited_status and invite_status.