Objective-C Dot Syntax and Init

后端 未结 2 453
臣服心动
臣服心动 2020-12-05 12:03

I have read a number of snippets that mention you should never use dot-notation within your init or dealloc methods. However, I can never seem to find out why. One post did

2条回答
  •  借酒劲吻你
    2020-12-05 12:44

    Firstly, it's not the dot notation specifically, it's the accessors that you shouldn't use.

    self.foo = bar;
    

    is identical to

    [self setFoo: bar];
    

    and they are both frowned upon within init/dealloc.

    The main reason why is because a subclass might override your accessors and do something different. The subclass's accessors might assume a fully initialised object i.e. that all the code in the subclass's init method has run. In fact, none of it has when your init method is running. Similarly, the subclass's accessors may depend on the subclass's dealloc method not having run. This is clearly false when your dealloc method is running.

提交回复
热议问题