The normal way to initialise and allocate in Objective-C is
NSObject *someObject = [[NSObject alloc] init];
Why is the following not practised
The main problem is that you might end up using the wrong object.
init
is special in many classes as it might just release the receiver and instead create a new object that resides at a different address. So your someObject
then points to the wrong (uninitialized) instance.
There are a lot of framework classes that use the arguments of the init
method to decide which kind of specialized subclass is best to use. This frequently happens with class clusters like NSString
or NSArray
but it can really happen with each kind of object.
One place where you can see this special behavior of initializers is ARC: It explicitly declares that the init family of methods eats up the receiver and returns a +1 retained object. This would not be necessary if initializers would just always return the receiver.
Of course you could fix your code by just doing another assignment:
NSObject *someObject = [NSObject alloc];
someObject = [someObject init];
This would fix the problem. But there's also no sense in doing it.