Вопрос

In Objective-C 2.0 I am assigning a value to an NSNumber property:

myObject.myProperty = 5;

The compiler tells me:

Implicit conversion of 'int' to 'NSNumber *' is disallowed with ARC

So I thought, what happens if I do this:

myObject.myProperty = @5;

Inspecting the property in the debugger shows:

_myProperty = (__NSCFNumber *) (int)5

This makes the compiler happy and nothing bad seems to happen, but I don't really understand what's happening.

What exactly does this shorthand do, and is it safe? What is NSCFNumber? I don't see it in the docs.

Это было полезно?

Решение

An NSNumber is an object, an int is a primitive value. You can box up a primitive into an NSNumber.

You might do this if you want to convert the int to a float or other primitive type, or because you need an object representation of the primitive value. Some classes like NSDictionary won't let you use primitive values as their keys, for example.

@5 is a shorthand for [NSNumber numberWithInt:5] and you can read more about literals on NSHipster. It is completely safe and designed to make your code quicker to type and easier to read!

NSCFNumber is the class Apple actually use to implement NSNumber behind the scenes, as part of what's known as a class cluster. At this stage, you don't need to worry about it.

Другие советы

It isn't just safe, it's correct. It wouldn't work if it wasn't a supported feature of the compiler. It's called a literal number definition. Just like literal string (@""), dictionary (@{}) and array (@[]).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top