1

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.

1
  • You need a refresher course on what an object is. Commented Jan 28, 2015 at 20:13

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! This solved my problem. Can you explain why the "removeAllObjects" did not work?... I think I'm seeing something I missed before, the actual object is added to the array, not copied to the array, so I have create the new object each time! As you can tell I've just started OOL. Thanks again.
When you call [starCatalogData addObject:startCatelogEntryData], no copy is made. You simply add a reference to the entry array. So when you add it a second time, you have now added two references to the same array. So when you call removeAllObjects, it removes all objects from the one array that has two references (not copies) of the array. This is why you need a completely new array each time.
Thanks for the quick help. This has been a real demystifier!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.