views:

46

answers:

1

Hi,

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>
            <innerDict1>
            <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

+3  A: 

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.

Yuji
Wow thank you for the quick and accurate response! You were right, it was that I had added the same instance of the innerArray to each outerDict. Problem solved.
mag725
We in SO are trained to read your mind:)
Yuji