我是来自 Python 世界的开发人员,习惯于使用异常。我在很多地方发现在这里使用异常并不是那么明智,并在需要时尽力转换为 NSErrors。但后来我遇到了这个:
NSMutableArray *results;
for (NSDictionary *dict in dicts)
{
// Memory management code omitted
SomeModel *model = [[SomeModel alloc] init];
model.attr1 = [[dict objectForKey:@"key1"] integerValue];
model.attr2 = [[dict objectForKey:@"key2"] integerValue];
model.attr3 = [[dict objectForKey:@"key3"] integerValue];
model.attr4 = [[dict objectForKey:@"key4"] integerValue];
[results addObject:model];
}
dict 中的某些对象包含 NSNull,这将导致“无法识别的选择器”异常。在那种情况下,我想完全放弃那个数据。我的第一直觉是将 for 块的全部内容包装到 @try-@catch 块中:
NSMutableArray *results;
for (NSDictionary *dict in dicts)
{
@try
{
SomeModel *model = [[SomeModel alloc] init];
model.attr1 = [[dict objectForKey:@"key1"] integerValue];
model.attr2 = [[dict objectForKey:@"key2"] integerValue];
model.attr3 = [[dict objectForKey:@"key3"] integerValue];
model.attr4 = [[dict objectForKey:@"key4"] integerValue];
[results addObject:model];
}
@catch(NSException *exception)
{
// Do something
}
}
但这是一个好方法吗?如果不对每个变量进行重复检查,我就无法提出解决方案,这真的很难看 IMO。希望有我没有想到的替代方案。提前致谢。