Ken Chatfield
Ken Chatfield

Reputation: 3287

Re-initializing an object

I have an object with a bunch of custom properties which I set up in the init method. At some point I'd like to reset the object to it's original state. It's stated in Apple's documentation that init should never be called separate from alloc, so using ARC, this seems to me to be a perfectly reasonable way to do it to me:

MyObject* myObject = [[MyObject alloc] init]; // inits myStringProperty to @""
myObject.myStringProperty = @"Hello world!";
NSLog(myObject.myStringProperty);

myObject = [[MyObject alloc] init]; // resets myStringProperty back to @""
NSLog(myObject.myStringProperty);

However, I've read (for example here) that a common pattern in this case is to explicitly define a reset method and refactor the re-initialisation code to there. Obviously this avoids having to create a whole new object (although I can't imagine the overhead of this is so high and leaving the release and re-allocation to ARC seems to be the simplest way) but is there any other reason for preferring one method over another? What is the general Objective C pattern for object re-initialization?

Upvotes: 4

Views: 965

Answers (1)

Brian
Brian

Reputation: 15706

If your primary purpose in creating a reset method is to avoid the overhead of releasing and allocating a new object, then I would say skip the reset method in most cases. Unless initializing your object is very complicated or time-consuming, this is a useless micro-optimization. Keep your class (and the code that uses it) simpler and just create a new object when you need a new object.

The only example I can think of for an Objective-C class that is reused is a UITableViewCell. There is a good reason to make these reusable, since it avoids degrading scrolling performance.

Upvotes: 6

Related Questions