When to use self on class properties?

前端 未结 8 1320
暗喜
暗喜 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:27

    This is an old question, though it used to be "When do I write [self setMyProperty:@"hi there"]?" (Note that self.MyProperty = @"hi there" is exactly equivalent to this.)

    The answer I've always heard (and which makes good sense) is always use the accessor; never write MyProperty = @"hi there". There are several reasons:

    1. Memory management is handled for you; you don't have to worry about proper retaining/releasing/copying.
    2. It's easier to modify your code in the future; if at some point you realize that changing MyProperty needs to have a particular side effect, you can add to the setter method without finding every time you set MyProperty.
    3. If you ever have problems with MyProperty, it's easy to add logging code to the setter (or even getter) to find out every time it's changed (or even accessed).

    Summary: it's safest and most flexible to always use [self setMyProperty:@"hi there"] or self.MyProperty = @"hi there", and never use MyProperty = @"hi there".

提交回复
热议问题