简体   繁体   中英

Problem with int in Objective C

singelton.categoryId = (int)[categories.categoriesId objectAtIndex:indexPath.row];
NSLog(@"%d", singelton.categoryId);

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]);

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 .

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];

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--ie, 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 ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM