I'm trying to execute what seems like simple code related to NSMutableArray and I've hit a wall. Here's my code:
NSMutableArray *newArray = [[[NSMutableArray alloc] initWithCapacity:4] retain];
NSArray *existingSection2 = [[NSArray alloc] initWithObjects:@"S2 Item1",@"S2 Item2",@"S2 Item3",@"S2 Item4",nil];
for (int i=0; i<[existingSection2 count]; i++) {
NSString *val = [[NSString alloc] initWithString:[existingSection2 objectAtIndex:i]];
[newArray addObject:val];
NSLog(@"val %i is %@ new array now contains: %@",i,val,[newArray objectAtIndex:i]);
NSLog(@"new array description: ",[newArray description]);
}
NSLog(@"what's in newArray: ",[newArray objectAtIndex:0]);
As I understand it, here's what I'm doing:
1) Allocate a new NSMutableArray called newArray with a capacity of 4
2) Allocate an NSArray called existingSection2 with four NSString values
3) Iterate through each of the four NSStrings in existingSection2
3a) Allocate an NSString called val with the contents of the existingSection2 array at position i
3b) Add val to newArray in the next available position
3c) Log some stuff for debugging
4) Log the final contents of newArray for debugging
This code is in application:didFinishLaunchingWithOptions: but here's what my console window shows when I launch in the Simulator:
2011-06-26 15:50:48.203 ArrayTest[14936:207] val 0 is S2 Item1 new array now contains: S2 Item1
2011-06-26 15:50:48.205 ArrayTest[14936:207] new array description:
2011-06-26 15:50:48.205 ArrayTest[14936:207] val 1 is S2 Item2 new array now contains: S2 Item2
2011-06-26 15:50:48.205 ArrayTest[14936:207] new array description:
2011-06-26 15:50:48.206 ArrayTest[14936:207] val 2 is S2 Item3 new array now contains: S2 Item3
2011-06-26 15:50:48.206 ArrayTest[14936:207] new array description:
2011-06-26 15:50:48.206 ArrayTest[14936:207] val 3 is S2 Item4 new array now contains: S2 Item4
2011-06-26 15:50:48.206 ArrayTest[14936:207] new array description:
2011-06-26 15:50:48.207 ArrayTest[14936:207] what's in newArray:
I don't understand why I'm not filling up newArray with those four new NSString objects! I've been searching SO for similar questions, but the answers all seem to be related to not initializing an NSMutableArray which I believe that I'm doing correctly.
Thanks for any help!
initWithCapacity:isn't terribly useful beyond cases where you have a couple of thousand objects and the hint means that the mutable array might not have to copy the backing store once during object addition.