Search code examples
objective-cnsmutablearraygnustep

Shouldn't NSMutableArray retain added objects?


Hi I am facing an issue with Linux / GNUstep. My NSMutableArray(s) do not seem to retain any added objects to them. Shouldn't they? Example:

NSString * str = @"test";
NSMutableArray * arr = [[NSMutableArray alloc] init];
NSLog(@"before add retainCount: %d", [str retainCount]);
[arr addObject: str];
NSLog(@"after add retainCount: %d", [str retainCount]);

Output:

before add retainCount: 1
after add retainCount: 1

Solution

  • (First: You should never rely on -retainCount.)

    Under the hood, constant strings (strings defined as, e.g., @"foo") are special in that -retain and -release don't actually do anything; they're always around with a retain count of 1 as an optimization.

    If you do something like:

    NSString * str = [NSString stringWithFormat:@"%@%@", @"foo", @"bar"];
    

    You may see what you expect.