Objective C convert number to NSNumber
Use this:
[p setAge:[NSNumber numberWithInt:10]];
You can't cast an integer literal like 10
to a NSNumber*
(pointer to NSNumber
).
In a sort of symmetry with your earlier question, NSNumber
is an object type. You need to create it via a method invocation such as:
[p setAge:[NSNumber numberWithInt:10]];
Your current code is attempting simply to cast the arbitrary integer 10
to a pointer. Never do this: if the compiler didn't warn you about it, you would then be trying to access some completely inappropriate bytes at memory location 10
as if they were an NSNumber
object, which they wouldn't be. Doing that stuff leads to tears.
Oh, and just to preempt the next obvious issues, remember that if you want to use the value in an NSNumber
object, you need to get at that via method calls too, eg:
if ( [[p age] intValue] < 18 )
...
(NSNumber
is immutable, and I think it is implemented such that identical values are mapped to the same object. So it is probably possible to get away with direct pointer comparisons for value equality between NSNumber
objects. But please don't, because that would be an inappropriate reliance on an implementation detail. Use isEqual
instead.)
Today it is also possible to do it using shorthand notation:
[p setAge:@(10)];