Would it be correct/ellegant use only alloc without init?

后端 未结 4 814
[愿得一人]
[愿得一人] 2020-12-28 23:48

If we don\'t want to implement init method in our class, and bearing in mind that init in NSObject only returns an instance of the object without initialization, I don\'t se

4条回答
  •  醉酒成梦
    2020-12-29 00:13

    No, just calling alloc would not be correct. alloc zeroes out all instance variables of the object, init then has the chance to set all or some instance variables to their default values. Some classes even use their init methods to create another instance and return that one instead of the one you allocated.

    Many classes expect that their init methods get called and would possibly cause crashes if you don't call init. If you are talking about a custom class that inherits directly from NSObject and needs no initialization of instance variables, you might get away with [myClass alloc] but it is definitely not good programming style.

提交回复
热议问题