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

混江龙づ霸主 提交于 2019-12-18 11:36:53

问题


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 see the point of calling init if we already get the instance with alloc. I have tried and it works, but I am not sure it won't cause future problems.

myClass *newObject = [myClass alloc];

instead of:

myClass *newObject = [[myClass alloc] init];

Thanks a lot.


回答1:


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.




回答2:


I think that it is not a good idea.
Read Cocoa Design Pattern, especially the "Two stage creation"

You can also read this article http://www.informit.com/articles/article.aspx?p=1398610




回答3:


I think that it wouldn't matter much if you didn't implement a "- (id)init" because if you did, you would call NSObject's init method which just returns the same value you send to the method. Though it is a good idea to create your own init method to set your instance variable.



来源:https://stackoverflow.com/questions/4085968/would-it-be-correct-ellegant-use-only-alloc-without-init

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!