Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: Convert id to NSInteger

Tags:

objective-c

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!

like image 253
pixelfreak Avatar asked Jun 24 '11 23:06

pixelfreak


3 Answers

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.

like image 72
albertamg Avatar answered Nov 19 '22 15:11

albertamg


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.

like image 24
Dietrich Epp Avatar answered Nov 19 '22 16:11

Dietrich Epp


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.

like image 3
bbum Avatar answered Nov 19 '22 16:11

bbum