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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With