KerrM
KerrM

Reputation: 5230

Testing for type of class in objective-c

I've got this XML file that I am parsing using the parser here and I'm running into an issue. The parser takes the XML and creates a dictionary out of it if there is only one item in the XML with the same structure, or an array of dictionaries if there is more than one XML item. For example:

<root>
  <item>
    <attr1>Hello</attr1>
    <attr2>world!</attr2>
  </item>

Would create a dictionary. But:

<root>
  <item>
    <attr1>Hello</attr1>
    <attr2>world!</attr2>
  </item>
  <item>
    <attr1>Hello</attr1>
    <attr2>world!</attr2>
  </item>

Would create an array of dictionaries.

Now, how would I distinguish if the retrieved data is an NSDictionary or an NSArray? What do I set the results of the parser to? For example, right now I'm doing this:

id eventsArray = [[[[XMLReader dictionaryForXMLData:responseData error:&parseError] objectForKey:@"root"] objectForKey:@"events"] objectForKey:@"event"];
if([eventsArray isMemberOfClass:[NSDictionary class]]) {
  //there's only one item in the XML
} else {
  //there's more than one item in the XML
}

But that doesn't work. So, how would I check what type of object eventsArray is?

Thanks!

Upvotes: 2

Views: 276

Answers (2)

Tony Million
Tony Million

Reputation: 4296

Try out this link:

if([eventsArray isKindOfClass:[NSDictionary class]]) {
  //there's only one item in the XML
} else {
  //there's more than one item in the XML
}

Hope this helps.

Upvotes: 3

NSProgrammer
NSProgrammer

Reputation: 2396

I'd do:

if ([eventsArray isKindOfClass:[NSArray class]])
////
else if ([eventsArray isKindOfClass:[NSDictionary class]])
////
else
////

Upvotes: 0

Related Questions