我正在尝试在应用程序从Web服务器获得响应时更新我的本地数据库。当应用程序从Web服务器获取更新时,我通过将id与响应匹配来获取本地数据库中的数据,并获取一行并执行更新代码,但本地数据库不会更新,也不会出错。 应该是什么解决方案???
-(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]);
}
// }
}
}
答案 0 :(得分:0)
您无法在stringWithFormat
中使用predicateWithFormat
。你的谓词应该是这样的:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"user_id=%@ and event_id=%@",
[NSNumber numberWithInt:[[dictEvent valueForKey:@"user_id"] intValue]],
[NSNumber numberWithInt:[[dictEvent valueForKey:@"id"] intValue]]
];
答案 1 :(得分:0)
除了修改@Martin
建议的谓词外NSPredicate *predicate = [NSPredicate predicateWithFormat:@"user_id=%@ && event_id=%@",
[NSNumber numberWithInt:[[dictEvent valueForKey:@"user_id"] intValue]],
[NSNumber numberWithInt:[[dictEvent valueForKey:@"id"] intValue]]
];
请注意,在两种情况下,您使用非匹配键更新对象:这适用于id和event_id,以及invite_status和invite_status。