1

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?

6
  • Array object contains nil or [NSNull Null]? Commented Mar 29, 2013 at 19:52
  • Each of the objects is either nil or a real object. I just don't want to write 3 statements, can it be done with 1? Commented Mar 29, 2013 at 19:52
  • Can't be done that way, even (especially) with non-nil values. The last value in the list must always be nil. Commented Mar 29, 2013 at 19:54
  • (Can be done with one long, tortuous statement using ?:, but I'd hardly advise it. Sometimes you actually have to write more than one statement. (Be thankful you're not doing it in assembler.)) Commented Mar 29, 2013 at 19:56
  • I could add the nil objects to dictionary, than filter out nils - but this is not nice... Commented Mar 29, 2013 at 19:56

2 Answers 2

3

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 !)

Sign up to request clarification or add additional context in comments.

Comments

0

You can use:

[yourMainArray removeObjectIdenticalTo:[NSNull null]];

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

2 Comments

How did the nil values get into the array in the first place?
Yes, this is a chicken-and-egg problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.