1. Short-Circuiting Dictionaries & Ternary Operator Fun.

    Recently I had a problem where my NSDictionary was getting short-circutied. Let me explain, take the following code. Actual code changed to protect the innocent.


    NSDictionary *aDict = [NSDictionary dictionaryWithObjectsAndKeys: [fooObj fname], @”first_name”, [barObj lname], @”last_name”,nil];

    Now later this code was transmitted as a JSON object, and I noticed that in some cases the object would only contain first_name. It however would be properly formed.

    So what was going on? Turns out that in some cases [barObj lname] would return nil, effectively short-circuiting and closing the NSDictionary.

    So how you guard against this? One way is to make sure whatever object you put in is valid, and if it is nil, that it’s replaced with something that won’t short-circuit the dictionary.  So you could do this…

    NSDictionary *aDict = [NSDictionary dictionaryWithObjectsAndKeys: [fooObj fname] ? [fooObj fname] : @”“, @”first_name”, [barObj lname] ? [barObj lname] : @”“, @”last_name”,nil];

    Now that will work but its getting a bit verbose, and if the more common case that [barObj lname] actually returns a valid object you end up calling it again.  So here’s a little trick that will save you some cycles.
    NSDictionary *aDict = [NSDictionary dictionaryWithObjectsAndKeys: [fooObj fname] ? : @”“, @”first_name”, [barObj lname] ? : @”“, @”last_name”,nil];
    In the case that [barObj lname] returns a valid object you don’t need to call it again. In the case where you are doing this for a large dictionary this can really save you some cycles.