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 ?