15

For iOS, given some NSDictionary key/value pairs where strings values were added as NSString and int/float values were added as NSNumber, is there a way to test the data type of a value to see whether it is NSString or NSNumber?

Monolo
  • 18,205
  • 17
  • 69
  • 103
jsherk
  • 6,128
  • 8
  • 51
  • 83

2 Answers2

27

NSObject offers:

- (BOOL)isKindOfClass:(Class)aClass

if obj is the value you get out of the NSDictionary then checkout:

[obj isKindOfClass:[NSString class]]
[obj isKindOfClass:[NSNumber class]]

If you check for these and you don't expect anything but NSString or NSNumber in the dictionary, then I would add an NSAssert in the else block.

There's more comments here on nuances of NSString and NSCFString:

In Objective-C, how do I test the object type?

Community
  • 1
  • 1
bryanmac
  • 38,941
  • 11
  • 91
  • 99
8

Dictionary return an id you can check its class type as follows

if ([[dictionary valueForKey:@"key"] isKindOfClass:[NSString class]]) {
        NSLog(@"it is a string");
    }
    else {
        NSLog(@"it is number");
    }
Ab'initio
  • 5,368
  • 4
  • 28
  • 40