Sergey Aldoukhov
Sergey Aldoukhov

Reputation: 22744

How to add a number of objects skipping nil objects to NSMutableArray?

I need a method that would add a few objects (2-10) to my array, skipping these that are nils:

NSMutableArray *arr = [[NSMutableArray alloc] init];
[arr addObjectsSkipNils:obj1, obj2, obj3];

How I can write this method in an elegant way?

Upvotes: 1

Views: 136

Answers (2)

Martin R
Martin R

Reputation: 539685

This category method would work:

@interface NSMutableArray (MyAdditions)
- (void)addObjectsSkipNilsWithCount:(NSUInteger)count objects:(id)obj, ...;
@end

@implementation NSMutableArray (MyAdditions)

- (void)addObjectsSkipNilsWithCount:(NSUInteger)count objects:(id)obj, ...
{
    va_list ap;
    va_start(ap, obj);
    // First object:
    if (obj != nil)
        [self addObject:obj];
    // Remaining objects:
    for (NSUInteger i = 1; i < count; i++) {
        id myobj = va_arg(ap, id);
        if (myobj != nil)
            [self addObject:myobj];
    }
    va_end(ap);
}
@end

Example:

NSMutableArray *a = [NSMutableArray array];
[a addObjectsSkipNilsWithCount:3 objects:@"foo", nil, @"bar"];
NSLog(@"%@", a);
// Output: ( foo, bar )

You have to specify the number of objects explicitly, because nil cannot be used as terminator for the variable argument list. (And bad things can happen if the count is greater than the actual number of objects supplied !)

Upvotes: 3

Anoop Vaidya
Anoop Vaidya

Reputation: 46533

You can use:

[yourMainArray removeObjectIdenticalTo:[NSNull null]];

Now if you want to copy this to arr you can do quite easily.

Upvotes: 0

Related Questions