开发者

Getting count of children in NSDictionary when sometimes the element is an array and sometimes it's not

I have an NSDictionary that looks kind of like this:

list 
   {{
         -> id
         -> name
         -> color
   },
   {
          -> id
    开发者_JAVA技巧      -> name
          -> color
   }}

which works great when I loop through it! But unfortunately, sometimes, the structure looks like this:

list {
   -> id
   -> name
   -> color
}

Where there's only one result returned. So I need to know if there's one or if there's more than one result returned.

I tried checking for the number of results by seeing if the ID key exists in "list" but unfortunately when I do valueForKey I get back something like this for multiple results: (429, 24) and just 429 if there's only one result.

But I can't do a count on the 429 value obviously.

Here's one of the things I was trying to do, which works great for multiple results, but not if there's one.

NSInteger numResults = [[list valueForKeyPath:@"id.@count"] intValue];

Any idea how to find out if it's an set of results or just a single result? I don't have any control over the data as it comes from a JSON object via a web service.

I also tried using [list mutableArrayValueForKey:@"id"]; and that seems to still only return an array if there's more than one result. I assumed I'd get back an array with one element if there was only one element...but apparently not?


You can check which kind of object you are dealing with using isKindOfClass:

NSInteger numResults = 1;
if ([list isKindOfClass:[NSArray class]]) {
  numResults = [list count];
}


If I understand correctly, one result will actually give you an NSDictionary, but multiple results will give you an NSArray of NSDictionaries?

Assuming that is the case, you could check the type of object you have like this:

if ([list isKindOfClass:[NSDictionary class]]) {
    //  Must be single result
}
else {
    //  Multiple results case
}

Otherwise, if I've misunderstood, perhaps you could clarify.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜