Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 962
toupper Avatar asked Nov 03 '10 10:11

toupper


2 Answers

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.

like image 151
Ole Begemann Avatar answered Oct 20 '22 18:10

Ole Begemann


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

like image 29
Benoît Avatar answered Oct 20 '22 17:10

Benoît