Reputation: 61039
I know the correct way to initial a NSNumber is NSNumber *a = @1;
and when I declare NSNumber *a = 1;
, I will got the error
Implicit conversion of int to nsnumber is disallowed with arc
But I don't know why when I declare NSNumber *a = 0;
there is no error
In my case, I have write some function in NSNumber category and then
@0
, I can use the function in category normally 0
, I can use the function in category, no error happened but when run app, this function will never call Upvotes: 3
Views: 584
Reputation: 4096
A nil
value is the safest way to initialize an object pointer if you don’t have another value to use, because it’s perfectly acceptable in Objective-C to send a message to nil
. If you do send a message to nil, obviously nothing happens.
Note: If you expect a return value from a message sent to nil, the return value will be nil for object return types, 0 for numeric types, and NO for BOOL types. Returned structures have all members initialized to zero.
In the last Apple Doc Working with nil
Upvotes: 0
Reputation: 7552
The value 0 is synonymous with nil
or NULL
, which are valid values for a pointer.
It's a bit of compatibility with C that leads to this inconsistent behavior.
History
In the C language, there is no special symbol to represent an uninitialized pointer. Instead, the value 0 (zero) was chosen to represent such a pointer. To make code more understandable, a preprocessor macro was introduced to represent this value: NULL
. Because it is a macro, the C compiler itself never sees the symbol; it only sees a 0 (zero).
This means that 0 (zero) is a special value when assigned to pointers. Even though it is an integer, the compiler accepts the assignment without complaining of a type conversion, implicit or otherwise.
To keep compatibility with C, Objective-C allows assigning a literal 0 to any pointer. It is treated by the compiler as identical to assigning nil
.
Upvotes: 14
Reputation: 23016
Objective-C silently ignores method calls on object pointers with value 0
(i.e. nil
). That's why nothing happens when you call a method of your NSNumber
category pointer which you assigned the value 0
.
Upvotes: 0
Reputation: 27448
You can consider 0
as nil
or null
that can be assign to object
but 1
is integer and can't allow to object or non integer.
Upvotes: 1
Reputation: 52632
0 is a null pointer constant. A null pointer constant can be assigned to any pointer variable and sets it to NULL or nil. This was the case in C for the last 45 years at least and is also the case in Objective-C. Same as NSNumber* a = nil.
Upvotes: 3