nsnumber 超出范围问题
我试图使用 NSNumber *percent 来获取整数值 percentint,但它总是使其超出范围。。 Nslog日志是这样的:
整数num的值为4
整数num的值与NsNumber一起 78910432
我的代码是这样的:
在我的头文件中:
int percentint;
NSNumber *percent;
@property(nonatomic,retain) NSNumber *percent; //tried without using this too
在我的 .m 文件中:
@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);
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,retain) 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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试:
保留@synthesize百分比;在。
Try:
leaving the @synthesize percent; in.
用户@Felz 是正确的。为了获取
NSNumber
的值,您必须通过方法调用来检索它:您所做的是打印出
percent< 的指针地址/code>
请记住,
NSNumber *percent
表示百分比是一个指针,而不是一个值。User @Felz is correct. in order to get the value of a
NSNumber
, you must retrieve it with a method call:What you did instead, was print out the pointer address for
percent
Remember that
NSNumber *percent
means percent is a pointer not a value.就像其他用户暗示的那样,
NSNumber
不是一个整数,因为您试图在最后一个 NSLog 中调用它。要从 NSNumber 中获取 int 值,请使用[percent intValue]
。另一个注意事项:您不需要两次初始化百分比。第一次调用
numberWithInt:
就像执行分配/初始化/释放。另外,在使用完对象之前切勿释放它。
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.