Search code examples
objective-cfor-loopnsnull

Browsing an object's fields


In Objective C, I have an object e.g. Person with a lot of fields firstName, lastName, phoneNumber, address, city... and so on. These fields types are NSString and any of these could be nil.

Now I want to concatenate my field values in another NSString :

Person *p = ...
NSMutableString *s = [[NSMutableString alloc] init];
for (NSString *field in @[p.firstName, p.lastName, p.phoneNumber,
                          p.adress, p.city, ....more fields...]) {
    if ([field length] > 0) {
        [s appendFormat:@"%@\n", field];
    }
}

Issue is that this code crash whenever one of the field is nil. I have the exception :

[__NSPlaceholderArray initWithObjects:count:]: attempt to insert nil object 
from objects[0]'

How could I handle simply the case of nil values within my for loop ?


Solution

  • I agree with @TomPace's post, for this small number I would do a simple if/else.

    However, there may be times you do need to loop through a list of fields.

    It's a bad idea to blindly pull the values into an array as you could be trying inserting nil values into the array. In this case, it would be better to place the field names into a key array as strings and loop through the list using valueForKey: to access the values. I would possibly store the keys list somewhere else where it can be used again.

    Person *p = ...
    NSMutableString *s = [[NSMutableString alloc] init];
    
    NSArray *keys = @[@"firstName", @"lastName", @"phoneNumber", @"adress", @"city"];
    
    for (NSString *key in keys) 
    {
        NSString *value = [p valueForKey:key];
        if ([value length] > 0) {
            [s appendFormat:@"%@\n", value];
        }
    }