开发者

Adding NSArray to NSDictionary is causing problems

I'm writing an app in XCode 3.2.3 for iOS 4. In my code, I am creating an NSArray of NSDictionaries, each containing two key/value pairs, a string and an NSArray of NSDictionaries (kind of confusing, I know). Just to give you a visual, here is the structure:

<NSArray>
    <NSDictionary>
        <NSString/>
        <NSArray>
            <NSDictionary/>
            <NSDictionary/>
            ...
        </NSArray>
    </NSDictionary>
    ...
</NSArray>

What's weird is that when I add a new NSDictionary to the innermost NSArray, it seems to add the same dictionary to the NSArray contained within each of the outer NSDictionaries. Here's how I'm adding the innermost NSDictionary to the innermost NSArray:

[[outerDict objectForKey:@"innerArray"] addObject:innerDict];

So, just to recap, the output I want is something like this:

<outerArray>

    <outerDict1>
        <string>
        <innerArray1>
            <innerDict1>
            <innerDict2>
        </innerArray1>
    </outerDict1>

    <outerDict2>
        <string>
        <innerArray2>
            <innerDict3>
            <innerDict4>
        </innerArray2>
    </outerDict2>

<outerArray>

But what I'm actually getting is this:

<outerArray>

    <outerDict1>
        <string>
        <innerArray1>
            <innerDict1>
            <innerDict2>
            <innerDict3>
            <innerDict4>
        </innerArray1>
    </outerDict1>

    <outerDict2>
        <string>
        <innerArray2>
            <i开发者_开发问答nnerDict1>
            <innerDict2>
            <innerDict3>
            <innerDict4>
        </innerArray2>
    </outerDict2>

<outerArray>

Notice that the inner NSDictionaries are added to every innerArray. For the life of me I can't figure out why!!

Any help would be very greatly appreciated, thank you!

-Matt


You need to post more code.

[[outerDict objectForKey:@"innerArray"] addObject:innerDict];

adds innerDict only to innerArray in outerDict, nothing else.

That said, you might have put the same innerArray twice into two different outerDict, like this:

NSMutableArray* innerArray=[NSMutableArray array];

[outerDict1 setObject:innerArray forKey:@"innerArray"];
[outerDict2 setObject:innerArray forKey:@"innerArray"];

This adds the same innerArray twice, not two independent arrays. Then, if you modify the innerArray in outerDict1, that will modify the innerArray in outerDict2 too, because these two are the same arrays.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜