Objective C NSString* property retain count oddity
cocoa, cocoa-touch, ios, objective-c, xcode
Solution
You've got a reference to an immutable string. Assignment doesn't need to copy the value (the string data) since it's immutable. If you do a mutable operation, like value = [newValue uppercaseString] then it should copy the bits into value, and value's retain count incremented.
Problem
I have the following example class: Test.h: ``` @interface Test : UIButton { NSString *value; } - (id)initWithValue:(NSString *)newValue; @property(copy) NSString *value; ``` Test.m: ``` @implementation Test @synthesize value; - (id)initWithValue:(NSString *)newValue { [super init]; NSLog(@"before nil value has retain count of %d", [value retainCount]); value = nil; NSLog(@"on nil value has retain count of %d", [value retainCount]); value = newValue; NSLog(@"after init value has retain count of %d", [value retainCount]); return self; } ``` Which produces the following output: ``` 2008-12-31 09:31:41.755 Concentration[18604:20b] before nil value has retain count of 0 2008-12-31 09:31:41.756 Concentration[18604:20b] on nil value has retain count of 0 2008-12-31 09:31:41.757 Concentration[18604:20b] after init value has retain count of 2147483647 ``` I am calling it like: ``` Test *test = [[Test alloc] initWithValue:@"some text"]; ``` Shouldn't value have a retain count of 1? What am I missing? Thanks for your help.