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

2020-03-18 07:10发布

问题:

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.

回答1:

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;


回答2:

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.



回答3:

Interesting question. Personally I’d think twice before I started messing with this. It seems to be just begging for a new source of bugs while not bringing anything new that you could not obtain in a safer way. Maybe I just don’t understand what’s going on in alloc and init enough to play with those parts, but I’d found that “dumb” code generally makes me happier (KISS).



回答4:

It can do, if memory is highly constrained (as in an iPhone application) you can 'alloc' one (or a few) instances and then reuse them. You need to be careful about leaks though, as objects retained/created in init are often released/freed at the 'free' message.