Rectangle 27 1

ios Objective C NSString* property retain count oddity?


self.value = newValue;     // this is exactly equivalent to the next line
[self setValue:newValue];  // this is exactly equivalent to the previous line

Don't look at retain counts. They're not useful and will only mislead you you can't be certain that nothing else is retaining an object, that an object you get from somewhere isn't shared.

Furthermore, it's critical to understand the difference between properties of your objects and instance variables within your objects. In your question's code, you are assigning a value to an instance variable. That instance variable is just that: a variable. Assigning to it will behave like any other variable assignment. To use the property, you must use either dot syntax or bracket syntax to actually invoke the property's setter method:

Instead, concentrate on object ownership and follow the Cocoa memory management rules to the letter. That way your memory management will be correct no matter what optimizations Cocoa may be doing behind the scenes for you. (For example, implementing -copy as just -retain for immutable objects.)

The code generated for the dot syntax and the bracket syntax is identical, and neither will access the instance variable directly.

Note
Rectangle 27 1

ios Objective C NSString* property retain count oddity?


NSString* string = [[NSString alloc] initWithString: @"some text"];
Test* test = [[Test alloc] initWithValue: string];

If you want to use the property, you have to say "self.value = whatever" instead of just "value = whatever", which simply assigns the instance variable.

Try a dynamically allocated string instead and see what happens.

You are passing in a literal string. The compiler probably allocates it in static memory and sets the retain count to the maximum possible value.

done.. same error. i've also tried using the dynamic string code above.

it's allocating it in static memory even though i use the copy attribute on the property?

Note
Rectangle 27 1

ios Objective C NSString* property retain count oddity?


What would the point of that be? You can't change the value, so you may as well point at the static memory. Maybe worth trying changing the type to NSMutableString to see if you get the same behaviour.

You're passing in a string constant, which can't really be deallocated. I think that 2147483647 is probably UINT_MAX, which basically means that the object can't be released.

doesn't the copy attribute make a new copy not in static memory?

it's possible for a -copy to actually -retain the original when the original is immutable, so a -copy would be guaranteed identical.

Note