Creating an NSArray to represent values ​​that include nil

I have a data source method that requests NSArraynumbers; some may be nil, but I still need to return each value.

The method might look like this:

- (NSArray *)configurationValues:(Configuration *)configuration {
  ....  
  return [NSArray arrayWithObjects:value1, value2, value3, value4, nil];
}

If value3- nil, I must return {2, 3, (the object is zero), 3}.

Off course, I get exceptions because I cannot insert an object nil.

What I can do is check each object and insert some dummy number or NSNull, but for me it looks like a boilerplate and not very elegant.

I am trying to create a category for NSArraywhich will replace all values nilwith something else to avoid exceptions:

@implementation NSArray (Nullable)

+ (instancetype)arrayWithObjectsSafe:(id)firstObj, ... {
    NSMutableArray *array = [NSMutableArray array];
    va_list args;
    id  object;

    va_start(args, firstObj);

    while((object = va_arg(args, id))) {
        if (object) {
            [array addObject:object];
        } else {
            // Insert dummy element // stuck here
            [array addObject:[NSNull null]];
        }
        NSLog(@"OBJECT %@", object);

    }

    va_end(args);
    return [NSArray arrayWithArray:array];
}
@end

, , while nil, nil.

, NSArray nil?

+4
2

, nil . . , :

const id END_MARKER (__bridge id)(void *)-1;

, nil ( 0). :

while((object = va_arg(args, id)) != END_MARKER)

:

[NSArray arrayWithObjects:value1, value2, value3, value4, END_MARKER];

.

+4

, . NULL, . , [NSNull null].

, value1?: [NSNull null] value1.

0

All Articles