Saturday, September 28, 2013

why NSNumber didn't show correct number

Sorry, my company mac is English version, so I have to speak English in CSDN even though I'm Chinese.
Here is my code.

A.h
 # import  


@ Interface A: NSObject {
NSNumber * i;

}
@ Property (retain) NSNumber * i;

@ End

 # import "A.h" 


@ Implementation A
@ Synthesize i;

- (Void) dealloc {
[I release];
[Super dealloc];
}

 # import  
# Import "A.h"

int main (int argc, const char * argv []) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

A * a = [[A alloc] init];

NSNumber * i = [[NSNumber alloc] initWithInt: 123];

[A setI: i];

NSLog (@ "i is% d", [a i]);
[Pool drain];
return 0;
}


I expected "i is 123" in console, but I only got "i is 109952". Why


Reply:
[A i] returns a NSNumber pointer, you use% d output is of course is an integer pointer.
For all NSObject objects, all with% @ output:
NSLog (@ "i is% @", [a i]);
Or you want to use% d, it will turn into a value of type int:
NSLog (@ "i is% d", [a i]. IntValue);

No comments:

Post a Comment