What you've written is correct except for the final return _myString
statement.
When you call retain on string, you are incrementing that instance's reference count by one. Assinging the value of string to _myString
does not change the actual instance (now pointed to by both string
and _myString
), so a second retain is not necessary, and would be incorrect.
All that said, what you've got is sort of redundant. The reason for the if (_myString != string)
check is that if your setter is called with the same object you already have, you don't want to release that object before you've had a chance to retain it. The program will crash in that situation, because you release it, it gets deallocated, but you keep a reference to it and continue using it (sending it messages). Since the object is the same, you can avoid this problem by simply doing nothing if the argument to the function is the same as the current value of the instance variable. However, retaining the argument before you release the instance variable is another way of accomplishing the exact same thing.
So, you can do either this:
- (void)setMyString:(NSString *)string
{
if (_myString != string) {
[_myString release];
_myString = [string retain];
}
}
or this:
- (void)setMyString:(NSString *)string
{
[string retain];
[_myString release];
_myString = string;
}
I tend to favor the first approach because it is (very slightly) faster if the value is the same, and is a little simpler when written out. But really, it's up to personal preference, and the form in your original question is fine too.