开发者

Trouble converting NSNumber to int

Sorry about this silly question. I'm trying to learn objc and I'm unable to do a simple sum between 2 int values... In fact problem is bef开发者_如何学运维ore the sum.

I have an object that have an instance variable defined as a NSNumber and it's defined as a property as follows:

@interface MyObj : NSObject {
   NSNumber *count;
}
@property (readwrite, assign) NSNumber *count;
@end

@implementation MyObj
@synthetize count;
@end

Then I have a class that will consume MyObj:

- (void)total:(MyObj *)mobj {
   int count = [mobj.count intValue];

   NSLog(@"%@", mobj.count);
   NSLog(@"%@", count);

   int total = 10 + count;
   NSLog(@"%@", total);
}

The first NSLog prints the mobj.count nicely (let's say 5), but the second one, throws an EXC_BAD_ACCESS. And of course the program never reachs the sum.

So, what I'm doing wrong? I'm trying to convert it to a int based on this post.

TIA,

Bob


The specifier %@ is for printing Obj-C objects, and it asks for the object’s -description. The count in your code is an int. Use %i for ints. Check out NSLog() Specifiers.


Another possible problem:

@property (readwrite, assign) NSNumber *count;

you most likely want to use retain so it won't disappear out from under you (as a rule of thumb: use assign for primitive types, retain for objects)

@property (readwrite, retain) NSNumber *count;


NSLog(@"%@", count);

should be:

NSLog(@"%i", count);

because it's an int, not an object.

Also look at

NSLog(@"%@", total);

because its also not an object but an int


int count = [mobj.count intValue];

should be

count = [NSNumber numberWithInt:[mobj.count intValue]];

It shows there itself, count is a NSNumber, when you are trying to set it to an int.


in your NSLog try:

NSLog(@"%@", [count stringValue]);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜