Phan Van Linh Phan Van Linh - 1 year ago 80
iOS Question

Why NSNumber *a = 0 do not display error

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

  • If the value of NSNumber is
    , I can use the function in category normally

  • If the value of NSNumber is
    , I can use the function in category, no error happened but when run app, this function will never call

Avi Avi
Answer Source

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.


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download