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

If we do not want to implement the init method in our class and remember that init in NSObject returns an instance of the object without initialization, I do not see the init call point if we already get an instance with alloc. I tried and it works, but I'm not sure that this will not cause future problems.

myClass *newObject = [myClass alloc]; 

instead:

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

Many thanks.

+6
memory-management objective-c iphone cocoa-touch init
source share
3 answers

No, just calling alloc will be wrong. alloc resets all instance variables of the object, init , then has the option to set all or some instance variables to their default values. Some classes even use their init methods to create another instance and return it instead of the one you allocated.

Many classes expect their init methods to be called and may fail if you do not call init . If you are talking about a custom class that inherits directly from NSObject and does not need to initialize instance variables, you can leave with [myClass alloc] , but this is definitely not a good programming style.

+16
source share

I think this is not a good idea. Read the Cocoa Design Pattern, especially the “Create Two Steps”

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

+2
source share

I think it wouldn’t matter if you didn’t implement the “- (id)” initialization, because if you did, you would call the NSObject init method, which simply returns the same value that you send to the method. Although it is a good idea to create your own init method to set your instance variable.

0
source share

All Articles