Update: tested and verified my assumptions. NULL and nil are equivalent when methods are invoked against them, and categories can be used to implement class methods.

One of the handier methods in C# is String.IsNullOrEmpty, which returns true if the argument is either a null pointer or an empty string.

Objective-C could use something similar, or so I’ve thought. Now I’m not so sure; read on.

There are 4 distinct possibilities for a blank string, disregarding the 5th possibility of a string with nothing but whitespace:

  • @””, the empty string itself
  • nil, the empty object
  • NULL, the original null pointer from C
  • The singleton NSNull instance, used for collections which do not accept NULL or nil

The most useful thread on the subject I’ve found is on stackoverflow.

Someone in that thread proposed an isEmpty method defined via categories, but failed to take the obvious next step: rather than an instance method, which won’t be relevant if the object is nil, it should be a class method, as C# does it.

(This presumes that categories can be used to create class methods: I can find nothing to indicate that they can’t, but I’m Xcodeless while traveling and thus cannot verify.) (Edit: tested, verified.)

The downside, as alluded to in the thread, is that if you want to do something like this you should ask the question of why you need it in the first place. You may be getting sloppy with your code if you don’t know what to expect in a string value.

Given a variable a, for example, [a length] will return 0 for nil or a truly empty string. I presume it will return 0 for a NULL pointer as well, but I’d need to test that. (Edit: tested, verified.)

If you can’t get by with sending the length message and checking for 0, perhaps you’re doing it wrong.


Related content