When to use self on class properties?

前端 未结 8 1321
暗喜
暗喜 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.

提交回复
热议问题