开发者

Problem with int in Objective C

singelton.categoryId = (int)[categories.categoriesId objectAtIndex:indexPath.row];
NSLog(@"%d", singelton.ca开发者_JAVA百科tegoryId);

singelton.categoryId is from type int.

But when I try to print it number is random, but if I do this NSLog(@"%@", singelton.categoryId); the printed value is right.

I need to print it with %d.

Can someone help me?


Use intValue method to get the integer representation of a NSString/NSNumber. Try,

singelton.categoryId = [[categories.categoriesId objectAtIndex:indexPath.row] intValue];


I am assuming the array returns you an NSNumber. So try this out.

int catId = [ ((NSNumber*) [categories.categoriesId objectAtIndex:indexPath.row] ) intValue];
NSLog(@"%d, catId )


try the following:

NSLog(@"%d", [singelton.categoryId intValue]);


The category ID as returned by objectAtIndex: is an object, most probably an NSNumber. By casting it to int you get the address of the object, not the numeric value stored in it. The correct code would be something like this:

singleton.categoryID = [[… objectAtIndex:…] intValue];


Try do do this in this way:

singelton.categoryId = [[categories.categoriesId objectAtIndex:indexPath.row] intValue]

It's because you can't store ints in array - they must be NSNumbers.


There's no way that's coming from an int primitive type when it's a proper object (assuming that objectAtIndex behaves here as elsewhere in Objective-C--i.e., it's not your own method. So, you'll need to ask for the intValue:

[[categories.categoriesId objectAtIndex:indexPath.row] intValue]

if it is an available method. What class is categoriesID?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜