开发者

iPhone: Get value in multi-dimentional array

I have an array that is many levels deep and I am wondering what is the best way to get one of the child element values that is deep in my array.

开发者_如何转开发

I assume I need to use a recursive method, but what is the best way to do this? Or is there a faster way to do this?

The array comes from an XML Parser that I am using which builds everything into an array like this (using NSLog to show the structure):

{
        children =         (
                        {
                children =                 (
                                        {
                        children =                         (
                                                        {
                                children =                                 (
                                );
                                data = 12;
                                element = AssetID;
                            }
                        );
                        data = "";
                        element = "ns1:GetUserIdByUsernameResponse";
                    }
                );
                data = "";
                element = "SOAP-ENV:Body";
            }
        );
        data = "";
        element = "SOAP-ENV:Envelope";
    }

What I would like to get at is the AssetID data, which in this case is 12.


Looks like the parser is returning an NSDictionary for each element with a "children" key that is an NSArray of child elements.

If the response will always be in this format with the AssetID element always in this position, you can directly access it without using recursion or looping.

Use something like this:

//"parserResultObject is the object the parser returns to you
NSDictionary *bodyDict = [[parserResultObject objectForKey:@"children"] objectAtIndex:0];
NSDictionary *responseDict = [[bodyDict objectForKey:@"children"] objectAtIndex:0];
NSDictionary *assetIdDict = [[responseDict objectForKey:@"children"] objectAtIndex:0];

//assuming AssetID's data is stored as an NSNumber...   
int assetIdData = [[assetIdDict objectForKey:@"data"] intValue];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜