Alex Rivera | Logout

Check whether an object is an NSArray or NSDictionary

Asked 2011-10-25T07:37:26.687
46

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

Edit
Report

1 Answer

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
}
answered 2013-01-03T13:54:36.443

Your Answer