I am trying to make NSNumber *percent to get the integer value percentint but it keeps making it out of scope.. The Nslog logs are like this:
The value of integer num is 4
The value of integer num is with NsNumber 78910432
My code is this:
In my header file:
int percentint;
NSNumber *percent;
@property(nonatomic,re开发者_如何学Pythontain) NSNumber *percent; //tried without using this too
In my .m file:
@synthesize percent; //tried without using this too
percentint=4;
NSLog(@"The value of integer num is %i", percentint);
percent= [NSNumber numberWithInt:percentint];
percent= [[NSNumber alloc] initWithInt:percentint]; //tried without using this too.
[percent autorelease]; //tried without using this too.
NSLog(@"The value of integer num is with NsNumber %i", percent);
Try:
percentint=4;
NSLog(@"The value of integer num is %i", percentint);
self.percent= [NSNumber numberWithInt:percentint];
NSLog(@"The value of integer num is in array %@", self.percent);
NSLog(@"The value of integer num is in array %d", [self.percent intValue]);
leaving the @synthesize percent; in.
User @Felz is correct. in order to get the value of a NSNumber
, you must retrieve it with a method call:
int percentInt = 95;
NSNumber *percent = [NSNumber numberWithInt:percentInt];
int myint = [percent intValue];
What you did instead, was print out the pointer address for percent
NSLog(@"Percent Value: %d",[percent intValue]);
NSLog(@"Percent Address: 0x%X",percent);
Remember that NSNumber *percent
means percent is a pointer not a value.
Like the other user insinuated, NSNumber
is not an integer as you are trying to call it in the last NSLog. to get the int value out of a NSNumber, use [percent intValue]
.
Another side note: you don't need to initialize percent twice. The first call numberWithInt:
is like doing an alloc/init/release.
Also, never release an object before you are done with it.
精彩评论