As i was reading through the book on Objective-C, i came across an example that initialized a class as follows:
ClassName *p = [[ClassName alloc] init];
While it makes sense that first we need to allocate memory to store data ClassName has before initializing, the following works just as well:
ClassName *p = [ClassName alloc];
Is init always needed?
In theory, it’s not technically required. That’s because
NSObject‘sinitmethod is effectively justreturn self;. However, in practice, it’s absolutely essential. Objects perform internal setup inside theinitmethod – creating internal state, allocating private members, and generally getting ready for action. Theinitmethod may not even return the same object as you allocated.Think of it in two phases:
allocallocates memory, but that’s it – it’s analogous to Java’snew.initconfigures the state of the memory so that the object can perform it’s tasks – analogous to Java calling the constructor. Don’t leave it out!