NSDictionaray dictionaryWithObjectsAndKeys adding NULL value

Viewed 12056

I want to create a NSDictionary with +[NSDictionary dictionaryWithObjectsAndKeys:]. One of my keys has a string but the string can sometimes be nil. If the string is nil, any other value key pairs I put afterward will be ignored because the list is prematurely terminated. What is the standard way to deal with the possibility that there might be a value with nil in a NSDictionary?

4 Answers

I encounter a similar problem and google take me here. I need to add some kv into the dictionary whose value may be nil. Inspired by Trenskow's answer, I modify that function to support insert nil value, not terminate as before.

#define KV_END NSNull.null

NSDictionary *NSDictionaryOfKV(id firstKey, ...) {
    __auto_type dict = [NSMutableDictionary dictionary];

    va_list args;
    va_start(args, firstKey);

    for (id key = firstKey; key != NSNull.null; key = va_arg(args, id)) {
        id obj = va_arg(args, id);
        if (obj == NSNull.null) {
            break;
        }
        if (key) {
            dict[key] = obj;
        }
    }

    va_end(args);

    return dict.copy;
}
__auto_type value2 = nil;
__auto_type dict = NSDictionaryOfKV(key1, value1, key2, value2, key3, value3, KV_END);

You will got

{
  key1: value1,
  key3: value3
}

You can change the KV_END to anything you want.

This make sense when your value is a variable, you can use it as-is, don't need to wrap it or like value ?: NSNull.null.

Related