When to use self on class properties?

前端 未结 8 1318
暗喜
暗喜 2020-12-03 09:03

When is self needed for class properties? For example:

self.MyProperty = @\"hi there\";

vs

MyProperty = @\"hi there\";


        
相关标签:
8条回答
  • 2020-12-03 09:40

    The difference is that

    self.MyProperty = @"hi there"
    

    is dot-notation call that will call the generated accessor, which will handle the retain counts correctly (equivalent to [self setMyProperty:@"hi there"]), whereas

    MyProperty = @"hi there"
    

    is a direct assignment to your member variable, which doesn't release the old value, retain the new one, or do anything else your accessor does (e.g., if you have a custom setter that does extra work).

    So yes, there is a big difference in memory management and in behavior in general between the two. The latter form is almost always wrong, unless you know specifically why you are doing it and that you are handling the retain counts correctly yourself.

    0 讨论(0)
  • 2020-12-03 09:42

    If you use automatic Key-Value Observing (or any Cocoa technology that builds on it - like bindings, ...), it is also important use the setter. The observer would not receive any notification if you assign to the ivar. If you bind "MyProperty" to a NSTextfield and you change your "MyProperty" ivar via code, the bound textfield would still display the old value as it did not receive any change notification.

    0 讨论(0)
提交回复
热议问题