tags:

views:

203

answers:

1

I need to check the type of each element in an array...

for(id obj in items) {
    if([obj isKindOfClass:[NSString class]]) {
       //handle string case
    } else if([obj isKindOfClass:[NSInteger class]]) {  //THIS LINE GIVES ERROR
       //handle int case
    }
}

Of course NSInteger is just an alias for int, so how can I check for this at runtime?

+1  A: 

You can't actually store NSInteger in an NSArray, since it isn't an object. If you are storing numbers in your array, they are most likely instances of NSNumber, so you would check for:

if ([obj isKindOfClass:[NSNumber class]]) { ... }

iPhone Developer Tips gives a good summary of the difference between NSInteger and NSNumber.

e.James
ah, yeah that was a typo.How would you differentiate floats from ints in the array if using NSNumber?
Ben Scheirman
That gets a little more tricky. You can request the `objCType` of the `NSNumber`, and then test for 'i' or 'f'. See http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/Reference/Reference.html#//apple_ref/occ/instm/NSNumber/objCType
e.James
that'll do! thanks :)
Ben Scheirman
You're welcome :)
e.James
Although technically correct, this answer is leading you astray. There's rarely a reason to add this non-OO smell to your Cocoa code. With the ability to add categories to existing classes, you can easily add a uniquePrefix_doMySpecialProcessing method to both NSString and NSNumber so that your loop can be properly polymorphic.
Barry Wark
in this particular case that seems more complex, when in fact I only need to check 3 or 4 types.It would help clean up the "is this NSNumber an int or a float" question though.
Ben Scheirman