开发者

Objective-C: Convert id to NSInteger

开发者 https://www.devze.com 2023-03-15 19:18 出处:网络
I have a dictionary with an NSNumber in it and I\'d like to convert it into NSInteger. Is the simplest/shortest way to do开发者_高级运维 this is to typecast into NSNumber and then calling integerValue

I have a dictionary with an NSNumber in it and I'd like to convert it into NSInteger. Is the simplest/shortest way to do开发者_高级运维 this is to typecast into NSNumber and then calling integerValue? Like so:

// newQuestion is an NSDictionary defined somewhere
NSInteger questionId = [(NSNumber *)[newQuestion objectForKey:@"question_id"] integerValue];

Is there a better way to do this? Thanks!


You can get rid of the cast if you want to make it shorter:

// newQuestion is an NSDictionary defined somewhere
NSInteger questionId = [[newQuestion objectForKey:@"question_id"] integerValue];

Since objectForKey: returns id, you can send it any known message and the compiler won't complain.


Yes, you don't need to cast.

NSInteger questionId = [[newQuestion objectForKey:@"question_id"] integerValue];

The cast doesn't actually do anything in this particular case. If the item in your dictionary is not a NSNumber (e.g., it's nil), then questionId will be 0.


Nope. That is the way to go. The question, though, is why do you need to turn into an integer in the first place? That may be avoidable. Or not.

0

精彩评论

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