how to convert NSNumber to int in Objective-C

为君一笑 提交于 2019-11-30 10:19:51

问题


Before putting int value into dictionary i have set the int value as [NSNumber numberWithInt:2], now when i try to retrieve back the dictionary content , i want it back in int format.. hw to do this??

here's my code;

NSMutabelDictionary *dict = [[NSMutableDictionary alloc]init];
int intValue = 300;

[dict setObject:[NSNumber numberWithInt:intValue] forKey:@"integer"];

retriving.........

int number = [dict ObjectForKey:@"integer"];

.. it throws an exception sayin casting is required.. when i do it this way..

int number = (int)[dict ObjectForKey:@"integer"];

stil it doesnt work...

how to solve this problem?/

please suggest..


回答1:


Have a look at the documentation. Use the intValue method:

int number = [[dict objectForKey:@"integer"] intValue];



回答2:


You should stick to the NSInteger data types when possible. So you'd create the number like that:

NSInteger myValue = 1;
NSNumber *number = [NSNumber numberWithInteger: myValue];

Decoding works with the integerValue method then:

NSInteger value = [number integerValue];



回答3:


Use the NSNumber method intValue

Here is Apple reference documentation




回答4:


A less verbose approach:

int number =  [dict[@"integer"] intValue];



回答5:


A tested one-liner:

int number = ((NSNumber*)[dict objectForKey:@"integer"]).intValue;


来源:https://stackoverflow.com/questions/3555906/how-to-convert-nsnumber-to-int-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!