I was using +[NSDictionary dictionaryWithObjectsAndKeys:] to make a new dictionary, but one of the objects in the dictionary was the result of a call to a method that was returning nil
, so the dictionary was incomplete.
This got me thinking about NULL
/nil
terminated argument lists. I don’t think they are a great idea (the compiler should be able to handle the list-termination for you!), but I think they are an especially bad idea in Objective-C.
The problem that it’s very common to have a nil
object in Objective-C, relative to, say C++. Many Cocoa methods return nil
on error. Since doing stuff with nil
(generally) won’t cause an exception, these nil
s stick around much longer then in other languages. As you can see, nil
is a pretty poor choice of a sentinel value.
It’s the 21st century! The compiler could tell an Obj-C method using a variable-argument-list how many arguments are in the list. This is trivial when all arguments are of type id
. Since Obj-C methods use a radically different syntax from C functions, it shouldn’t effect existing C-code. Unfortunately, I don’t see this being added, because Objective-C is already so mature.
In the meantime. Be a little more suspicious of any objective-C methods taking a NULL
-terminated list. I wish I had a perfect solution to avoid them, but I don’t! Sometimes they are the best way to do something. If you have a great work-around for constructing, say an NSDictionary
with a variable number of key/values please let me know!
I don’t see what’s wrong with them, except that I didn’t know about this until I started getting a weird run-time error. Then someone on IRC revealed that UIAlert uses a nil-terminated list for button labels. That fixed my problem. So beyond throwing off newbies like myself, I don’t see it as a big deal.
Comment by Elliot Lee — August 15, 2008 @ 4:15 am