Beginner question here:
I’m trying to understand the some basic memory management. if I’m overriding a setter method, does the following adequately handle the memory management of the incoming string?
- (void)setMyString:(NSString *)string
{
if (_myString != string){
[string retain];
[_myString release];
_myString = string;
}
}
My logic here is that as soon as we enter into that if statement, i want to take ownership of the incoming string, hence the retain. Next I release the _myString object. Then i set the _myString object to the string object. Here is the source of my confusion: do I need to retain the myString object at this point? or do i already have ownership over it as a result of setting it equal to the string object?
Thanks!
What you’ve written is correct
except for the final.return _myStringstatementWhen you call retain on string, you are incrementing that instance’s reference count by one. Assinging the value of string to
_myStringdoes not change the actual instance (now pointed to by bothstringand_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:
or this:
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.