NULL vs nil in Objective-C

Objective CCocoaNull

Objective C Problem Overview


In observeValueForKeyPath:ofObject:change:context: - why do the docs use NULL instead of nil when not specifying a context pointer?

Objective C Solutions


Solution 1 - Objective C

nil should only be used in place of an id, what we Java and C++ programmers would think of as a pointer to an object. Use NULL for non-object pointers.

Look at the declaration of that method:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
    change:(NSDictionary *)change context:(void *)context

Context is a void * (ie a C-style pointer), so you'd definitely use NULL (which is sometimes declared as (void *)0) rather than nil (which is of type id).

Solution 2 - Objective C

They're technically the same thing (0), but nil is usually used for an Objective-C object type, while NULL is used for c-style pointers (void *).

Solution 3 - Objective C

They're technically the same thing and differ only in style:

  • Objective-C style says nil is what to use for the id type (and pointers to objects).
  • C style says that NULL is what you use for void *.
  • C++ style typically says that you should just use 0.

I typically use the variant that matches the language where the type is declared.

Solution 4 - Objective C

NULL is the C equivalent of nil, a pointer to nothing;

where nil is zero typed as id,

NULL is zero typed as void*.

One important point you can’t send a message to NULL. So it is preferred to use nil in objective-C at many places.

Solution 5 - Objective C

They almost are the same thing except,

nil is used in an Objective-C style. where NULL is for C type pointers and is typdef'ed to (void *).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionerikpriceView Question on Stackoverflow
Solution 1 - Objective CPaul TomblinView Answer on Stackoverflow
Solution 2 - Objective CMarc CharbonneauView Answer on Stackoverflow
Solution 3 - Objective CAndrewView Answer on Stackoverflow
Solution 4 - Objective Cuser2560622View Answer on Stackoverflow
Solution 5 - Objective Cdan14941View Answer on Stackoverflow