开发者

Objective C convert number to NSNumber

开发者 https://www.devze.com 2023-01-29 10:43 出处:网络
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.

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];
}


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)];


Use this:

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

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


NSNumber *yourNumber = [NSNumber numberWithInt:your_int_variable];


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]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号