I'm writing a method and I want to return an object or lack of object if the method cannot find what it needs to. What's the best practice to return a lack of object, should it be [NSNull null]
or nil
? or it doesn't make any difference?
Asked
Active
Viewed 238 times
1

Aaron Brager
- 65,323
- 19
- 161
- 287

Phil
- 2,995
- 6
- 40
- 67
-
3See this NSHipster article on the differences between nil, Nil, NULL, and NSNull: http://nshipster.com/nil/ – Scott Berrevoets Jun 06 '13 at 14:10
-
Also worth reading the NSNull Class Reference: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNull_Class/Reference/Reference.html – Aaron Brager Jun 06 '13 at 14:25
-
See also http://stackoverflow.com/questions/6814427/what-are-the-differences-between-nil-null-and-nsnull-nil – Brian Jun 06 '13 at 14:37
1 Answers
9
The convention is to return nil
for Objective-C pointers (e.g. where the type is id
, NSSomething *
, UISomething *
, etc.), NULL
for arbitrary C pointers (e.g. int*
, struct MyStruct*
, void (*)(int)
.
[NSNull null]
is only useful when you want to put a null value into an NS
collection like NSArray
or NSDictionary
. So, [NSNull null]
is a singleton Objective-C object that represents the null value (or the absence of value) by convention, there's nothing special about it otherwise.

Alexei Sholik
- 7,287
- 2
- 31
- 41
-
Just one hint, pay attention that if you put Nil in a collection you create an exception and the app will crash, so it really depends on the purpose of the method. – Andrea Jun 06 '13 at 14:22
-
Which is the reason you test for nil before adding the returned object to a collection and is a standard idiom. – uchuugaka Jun 06 '13 at 16:17