Home > Enterprise >  Why does [[NSNumber alloc] init] return nil?
Why does [[NSNumber alloc] init] return nil?

Time:11-09

I know I should use the designated initializer to init a NSNumber. But when I find that: [[NSNumber alloc] init] returns nil, I am still a little surprised. What has been done in implementation of NSNumber to return nil for init (after all, NSObject will return self)? Does it try to init the underlying __NSCFNumber at first in the designated initializers? So if you go through the default init, it returns nil as the underlaying __NSCFNumber is nil. Why doesn't it just declare the init and new as NS_UNAVAILABLE?

CodePudding user response:

I suspect that the overridden init for NSNumber simply returns nil. This is valid if an object cannot be created for some reason.

It isn't valid to call this initialiser as an object cannot be created without knowing what sort of number you want.

The reason that it isn't marked as NS_UNAVAILABLE is that that macro was only introduced in 2014.

NSNumber is much older than that. 20 years older. It dates back to NeXTSTEP from 1994 (That is what the NS prefix means on all of those classes). Adding that macro would be a breaking change.

  • Related