NSMutableArray and Adding Potentially Released Objects

So, here’s an experiment. I’m starting some long path towards learning Objective-C. I’m trying to wrap my mind around memory management (I still have a mortal fear of pointers) and I came up with this example.

    NSMutableArray * testArray = [NSMutableArray array];
 
    NSString * string1 = [[NSString alloc] init];
    string1 = @"Test String 1";
 
    NSString * string2 = [NSString stringWithString:@"Test String 2"];
    NSString * string3 = [NSString stringWithString:@"Test String 3"];
 
    [testArray addObject:string1];
    [testArray addObject:string2];
    [testArray addObject:string3];
 
    NSEnumerator * arrayEnum = [testArray objectEnumerator];
    id eachObject;
    while((eachObject = [arrayEnum nextObject]))
    	NSLog(eachObject);
 
    NSLog(@"Array count: %i", [testArray count]);	
    NSLog(@"Releasing string 1 ...");
    [string1 release];
    NSLog(@"Array count: %i", [testArray count]);	
 
    arrayEnum = [testArray objectEnumerator];
    while((eachObject = [arrayEnum nextObject]))
    	NSLog(eachObject);

As you see, it allocs an NSString, and adds it, along with some other objects, to an NSMutableArray. Then we release the first string we added to the NSMutableArray. So what happens to the array?

Test String 1
Test String 2
Test String 3
Array count: 3
Releasing string 1 ...
Array count: 3
Test String 1
Test String 2
Test String 3

So do objects get copied when they’re added to an NSMutableArray? It appears so.

2 Comments

  1. Gus posted June 1, 2008, 1:18 pm

    They don’t get copied, but I believe they are retained by the array - so your release call decreases the reference count from 2 to 1.

  2. Ardekantur posted June 1, 2008, 8:18 pm

    Gus:

    I considered this, but I just ran another test that changed string1 into another string value, and the string in the NSMutableArray stayed the original value of string1. So I’m not sure.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*