Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it ever make sense to call [init] outside of [[alloc] init]?

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.

like image 371
iter Avatar asked May 02 '10 06:05

iter


2 Answers

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;
like image 192
bbum Avatar answered Sep 21 '22 17:09

bbum


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.

like image 20
drawnonward Avatar answered Sep 19 '22 17:09

drawnonward