Rebol Tutorial
Rebol Tutorial

Reputation: 2754

Objective C convert number to NSNumber

Why doesn't this please the compiler? Casting is supposed to work like in C as I can read here How to cast an object in Objective-C.

[p setAge:(NSNumber*)10];

where

- (NSNumber*) age {
    return _age;
}
- (void) setAge: (NSNumber*)input {
    [_age autorelease];
    _age = [input retain];
}

Upvotes: 27

Views: 51754

Answers (5)

Luda
Luda

Reputation: 7078

NSNumber *yourNumber = [NSNumber numberWithInt:your_int_variable];

Upvotes: 6

Maxim Chetrusca
Maxim Chetrusca

Reputation: 3352

Today it is also possible to do it using shorthand notation:

[p setAge:@(10)];

Upvotes: 32

walkytalky
walkytalky

Reputation: 9543

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.)

Upvotes: 57

Stephen Darlington
Stephen Darlington

Reputation: 52565

Because NSNumber is an object and "10" in a primitive integer type, much like the difference between int and Integer in Java. You, therefore, need to call its initialiser:

[p setAge:[NSNumber numberWithInt:10]

Upvotes: 5

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181430

Use this:

[p setAge:[NSNumber numberWithInt:10]];

You can't cast an integer literal like 10 to a NSNumber* (pointer to NSNumber).

Upvotes: 6

Related Questions