user4268271
user4268271

Reputation:

add an array to another array in iOS

I have a strange problem because "addObject" is working to add an NSString but not to add an NSArray:

    NSMutableString *starCatalogEntryValue = [[NSMutableString alloc] init]; // a single string from a catalog
    NSMutableArray *starCatalogEntryData = [[NSMutableArray alloc] init]; // array of strings
    NSMutableArray *starCatalogData = [[NSMutableArray alloc] init]; // array of arrays

loop i times {
    [starCatalogEntryData removeAllObjects];
    loop j times {
        [starCatalogEntryData addObject:starCatalogEntryValue]; // This works
    }
    [starCatalogData addObject:starCatalogEntryData]; // This does not work
}

Actually, adding the array starCatalogEntryData works but not properly. I end up with i entries in starCatalogData but they are all equal to the last value of starCatalogEntryData.

Upvotes: 1

Views: 1398

Answers (1)

rmaddy
rmaddy

Reputation: 318794

The problem is that you reuse startCatalogEntryData over and over. You want this:

NSMutableString *starCatalogEntryValue = [[NSMutableString alloc] init]; // a single string from a catalog
NSMutableArray *starCatalogData = [[NSMutableArray alloc] init]; // array of arrays

loop i times {
    NSMutableArray *starCatalogEntryData = [[NSMutableArray alloc] init]; // array of strings
    loop j times {
        [starCatalogEntryData addObject:starCatalogEntryValue]; // This works
    }
    [starCatalogData addObject:starCatalogEntryData]; // This does not work
}

This creates a new array each time.

Upvotes: 3

Related Questions