如果我在添加对象时保存在循环外部,而不是在循环中执行此操作,是否会丢失数据?要求外面保存要快得多。
外圈:
for(NSMutableDictionary *result in data){
[manager newManagedCaf];
for (NSString *name in result){
if ([name isEqualToString:@"contact"]){
NSNumber *num = [NSNumber numberWithInteger:[[result valueForKey:name] integerValue]];
[[manager cafCards] setValue:num forKey:name];
}
else{
[[manager cafCards] setValue:[result valueForKey:name] forKey:name];
}
}
[[manager cafCards] setValue:[NSNumber numberWithBool:YES] forKey:@"synced"];
}
}
if(![[manager cafCards].managedObjectContext save:&error]){
NSLog(@"Unable to save managed object context.");
NSLog(@"%@, %@", error, error.localizedDescription);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"Error: %@", [error localizedDescription]] message:@"Database not working, try again later or inform IT." delegate:self cancelButtonTitle:@"Back" otherButtonTitles:nil, nil];
[alert show];
[self getImages:0 con:con withManager:manager];
}
内圈:
for(NSMutableDictionary *result in data){
[manager newManagedCaf];
for (NSString *name in result){
if ([name isEqualToString:@"contact"]){
NSNumber *num = [NSNumber numberWithInteger:[[result valueForKey:name] integerValue]];
[[manager cafCards] setValue:num forKey:name];
}
else{
[[manager cafCards] setValue:[result valueForKey:name] forKey:name];
}
}
[[manager cafCards] setValue:[NSNumber numberWithBool:YES] forKey:@"synced"];
if(![[manager cafCards].managedObjectContext save:&error]){
NSLog(@"Unable to save managed object context.");
NSLog(@"%@, %@", error, error.localizedDescription);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"Error: %@", [error localizedDescription]] message:@"Database not working, try again later or inform IT." delegate:self cancelButtonTitle:@"Back" otherButtonTitles:nil, nil];
[alert show];
}
}
当我把错误处理放在外面时,得到以下错误:
[2664:3215894] Unable to save managed object context.
2017-06-07 14:48:22.644 [2664:3215894] (null), (null)
2017-06-07 14:48:22.778 [2664:3215894] This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes. This will cause an exception in a future release.
答案 0 :(得分:1)
没有数据丢失。
这甚至是批处理操作后提交数据(一次)的推荐方法。
但是你也应该在保存行之后移出显示Unable to save...
的错误处理。 (顺便说一句:UIAlertView
已被弃用了很长时间。)