I’m a developer from Python world used to using exceptions. I found in many places that using exceptions is not so wise here, and did my best to convert to NSErrors when needed. but then I encounter this:
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];
}
with some of the objects in dict containing NSNull, which would result an “unrecognized selector” exception. In that case, I want to drop that datum completely. My first instinct is to wrap the whole content of the for block into a @try-@catch block:
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
}
}
But is this a good approach? I can’t come up with a solution without repeating checks on each variable, which is really ugly IMO. Hopefully there are alternatives to this that haven’t occur to me. Thanks in advance.
Many people use a category on NSDictionary for these cases:
You still need to make sure, that your dict is an actual dictionary instance.