27

In Objective C?

Are they really the same thing?

How to test that an object is nil?

Lebyrt
  • 1,376
  • 1
  • 9
  • 18
user4951
  • 32,206
  • 53
  • 172
  • 282
  • possible duplicate of [iphone+Difference between nil,NIL and null](http://stackoverflow.com/questions/5908936/iphonedifference-between-nil-nil-and-null) – jscs May 10 '11 at 20:46
  • I found this answer very useful: http://stackoverflow.com/questions/1841983/what-describes-nil-best-whats-that-really – CRDave Sep 10 '12 at 10:08

3 Answers3

50

Nil and nil are defined to be the same thing (__DARWIN_NULL), and are meant to signify nullity (a null pointer, like NULL). Nil is meant for class pointers, and nil is meant for object pointers (you can read more on it in objc.h; search for Nil). Finally, you can test for a null value like this:

if (object == nil)

or like this:

if (!object)

since boolean evaluations will make any valid pointer that contains an object evaluate to true.

Itai Ferber
  • 28,308
  • 5
  • 77
  • 83
10

nil is the Objective-C constant for a null pointer to an object, Nil is identically defined. In practice, it is has the same value as the C constant NULL. Test for a nil object like this:

if (fooObj == nil)

In my code, I tend to use nil for Objective-C objects and NULL for other C pointers. This is a matter of personal taste - currently nil and NULL are interchangeable for comparison in all existing Objective-C implementations.

JeremyP
  • 84,577
  • 15
  • 123
  • 161
  • 7
    Actually, `Nil` is defined (it's the same as `nil`). Check out [objc.h](http://www.opensource.apple.com/source/objc4/objc4-371.1/runtime/objc.h). – Itai Ferber May 10 '11 at 11:04
  • +1 good answers. The other answer is also perfectly correct. +1 for great comments. Itai – user4951 Dec 13 '11 at 08:40
3
  • nil (all lower-case) is a null pointer to an Objective-C object.
  • Nil (capitalized) is a null pointer to an Objective-C class.
  • NULL (all caps) is a null pointer to anything else.
Carlos Avalos
  • 247
  • 4
  • 8