1

I often have custom classes in Objective C, such as a contact-class containing name, phone number, e-mail and so on, looking for instance like this:

NSString *firstName;
NSString *familyName;
NSString *emailAddress; 
...

In order to put these values into an array, I have to do this:

if (firstName) [someArray addObject:firstName];
if (familyName) [someArray addObject:familyName];
if (emailAddress) [someArray addObject:emailAddress];
...

Is there a way to do something more like:

for (not nil objects) {
    [someArray addObject:firstName];
    [someArray addObject:familyName];
    [someArray addObject:emailAddress];
    ...
}

where every line containing a nil object is ignored?

Jorn
  • 1,054
  • 9
  • 25
  • 1
    Array looses information. Why don't you use dictionary or send whole custom object? – Marek H Aug 21 '14 at 07:02
  • Adding nil object to dictionary also causes an exception. Also sometimes an array is useful, like when populating a UITableView using an array as data source. – Jorn Aug 21 '14 at 07:47
  • 1
    check setValue:forKey: This tests for nil values. Also check how to get property names programatically http://stackoverflow.com/questions/11774162/list-of-class-properties-in-objective-c – Marek H Aug 21 '14 at 08:09

1 Answers1

3

There are various ways of achieving this, depending on what static sugar you prefer.

First, you can implement a category on NSArray that will add addObjectIfNotNil: method, in which case your code will end up being:

[someArray addObjectIfNotNil:firstName];
[someArray addObjectIfNotNil:familyName];
[someArray addObjectIfNotNil:emailAddress];

If you want something less trivial, you can look at NSPredicate:

id v1 = @1, v2=@2, v3 = nil, v4 = @3, v5 = @4, v6 = nil;

NSPredicate* notnil = [NSPredicate predicateWithBlock:^BOOL(id obj, __unused NSDictionary* bindings) {
    return ![obj isEqual:[NSNull null]];
}];

NSArray* values = @[
    (v1) ?: [NSNull null],
    (v2) ?: [NSNull null],
    (v3) ?: [NSNull null],
    (v4) ?: [NSNull null],
    (v5) ?: [NSNull null],
    (v6) ?: [NSNull null],
];

values = [values filteredArrayUsingPredicate:notnil];
Andrey
  • 1,561
  • 9
  • 12