@property/@synthesize question

后端 未结 3 965
清歌不尽
清歌不尽 2021-01-31 12:39

I\'m going through all of my documentation regarding memory management and I\'m a bit confused about something.

When you use @property, it creates getters/setters for th

3条回答
  •  时光取名叫无心
    2021-01-31 13:15

    When you create a retain setter, you're creating something like this:

    - (void)setString:(NSString *)someString {
        if (someString != string) {
            [string release];
            [someString retain];
            string = someString;
        }
    }
    

    If you don't use the setter, the new value is not getting that retain—you don't "own" that string, and because it's all references, if the original string is released, you might be facing a null reference, which will lead to an EXC_BAD_ACCESS. Using the setter ensures that your class now has a copy of that value—so yes, it does increment the retain count of the new value. (Note that using the getter is a convention of OOP—that outsiders should not be able to directly touch the ivar. Also in your getter you can modify the value, maybe returning an NSArray when your ivar is an NSMutableArray, for example).

    You shouldn't autorelease in a setter—Apple has used it in their sample code, but a thing to keep in mind is that setters are called a lot—millions of times, potentially. All of those objects are going into the same autorelease pool, so unless you create your own and/or regularly flush it, you'll have a ton of elements in your pool, all unneeded but still taking up RAM. Much better to simply release.

    As for dealloc, trace back through that setter. If you send a release directly, it's obvious—you release that object. But if you write self.string = nil;, what you're doing is this:

    1. The nil value is not the same, so you enter the if block
    2. You release the old value—what you want to do
    3. You retain nil: messages to nil do nothing, and you don't crash
    4. You set nil, which doesn't take up any memory, to the string, which is now effectively empty

    As a matter of convention, I use release in my dealloc method, because release seems more final, and dealloc is the final method call your object will receive. I use self.string = nil; in viewDidUnload and the memory warning methods.

    Hope this helps!

提交回复
热议问题