45

As per subject, how can I check whether an object is an NSArray or NSDictionary?

Charles Yeung
  • 38,347
  • 30
  • 90
  • 130

4 Answers4

98
if([obj isKindOfClass:[NSArray class]]){
    //Is array
}else if([obj isKindOfClass:[NSDictionary class]]){
    //is dictionary
}else{
    //is something else
}
zakishaheen
  • 5,551
  • 1
  • 22
  • 29
14

Try

[myObject isKindOfClass:[NSArray class]]

and

[myObject isKindOfClass:[NSDictionary class]]

Both of these should return BOOL values. This is basic use of the NSObject method:

-(BOOL)isKindOfClass:(Class)aClass

For a bit more information, see this answer here: In Objective-C, how do I test the object type?

Community
  • 1
  • 1
Chris Grant
  • 2,463
  • 23
  • 27
8

Consider the case when you're parsing data from a JSON or XML response. Depending on the parsing library you are using, you may not end up with NSArrays or NSDictionaries. Instead you may have __NSCFArray or __NSCFDictionary.

In that case, the best way to check whether you have an array or a dictionary is to check whether it responds to a selector that only an array or dictionary would respond to:

if([unknownObject respondsToSelector:@selector(lastObject)]){

// You can treat unknownObject as an NSArray
}else if([unknownObject respondsToSelector:@selector(allKeys)]){

// You can treat unknown Object as an NSDictionary
}
Josh
  • 621
  • 6
  • 10
  • 2
    -1 Many objects may respond to the same selectors, especially something as generic as `lastObject` or `allKeys`. Using `isKindOfClass:` is clearly the way to go when dealing with class clusters like `NSArray` and `NSDictionary`. – Calrion Oct 29 '13 at 00:21
  • 2
    That answer is total nonsense. [myObject isKindOfClass:[NSArray class]] does correctly answer the question "will myObject behave as if it is an NSArray", and that's what you want. There is no selector that only an NSArray or NSDictionary would respond to. In two minutes I can create a class with instance methods "allKeys" and "lastObject". Or add "allKeys" as a category method to NSArray. – gnasher729 May 30 '14 at 14:49
0

Just in case anyone comes late to this party looking for a Swift equivalent, here you go. It's a lot more elegant than the Objective-C version, IMHO, because not only does it check the types, but it casts them to the desired type at the same time:

if let arrayVersion = obj as? NSArray {
    // arrayVersion is guaranteed to be a non-`nil` NSArray
} else if let dictionaryVersion = obj as? NSDictionary {
    // dictionaryVersion is guaranteed to be a non-`nil` NSDictionary
} else {
    // it's neither
}
NRitH
  • 13,441
  • 4
  • 41
  • 44