I am wondering if [[alloc] init]
is just a convention or if separating the two calls has wider use. For instance, I wonder if people ever call [init]
(or friends) on an existing object to "re-initialize" it.
The convention is to never ever re-initialize objects. You can do so on an extremely limited basis in your own classes that subclass NSObject (or defining a new root), but you should never do so with a subclass of any other class from the system frameworks.
If you want to "re-use" instances of a class, then provide methods for re-use beyond the designated initializer. I.e. you could do:
- (void) reset;
Or:
- (void) resetWithNewState: (MyState *) aState;
By convention, the only use of the init family is when they call each other. For example:
-(id) initWithSomething:(int)something {
self = [super init];
// use something
return self;
}
-(id) init {
return [self initWithSomething:3];
}
You might pass around a zombie object where init had never been called, but I cannot think of a good reason to do so. If you want to create an object without knowing the type, you pass around a Class.
-(id) makeAnything:(Class)someClass {
return [[someClass alloc] init];
}
Edit:
alloc
guarantees that all members are initialized to zero, and many init
methods rely on that. Calling init
more than once breaks that contract.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With