ricky3350
ricky3350

Reputation: 1738

Objective C initialization methods: alloc/init vs. other initializers

In Objective C, most objects are created by using [[ObjectType alloc] init]. I've also seen initializers that use [[ObjectType alloc] initWithOption1:...] (with parameters). But some classes are recommended to be initialized without using the alloc method, such as the new iOS 8 UIAlertController, which is initialized using the method [UIAlertController alertControllerWithTitle:message:preferredStyle:], or UIButton, which uses the buttonWithType: method. What are the advantages/disadvantages to doing this? How do I make an initializer like this?

Upvotes: 1

Views: 590

Answers (2)

nhgrif
nhgrif

Reputation: 62062

Assuming you're using ARC (and I can't find an excuse to not use ARC for any new project), there's going to be essentially no difference between the two approaches.

To create one of these factory methods, it's as simple as this...

Given the initializer method:

- (instancetype)initWithArgument1:(id)arg1 argument2:(id)arg2;

We create the following class method:

+ (instancetype)myClassWithArgument1:(id)arg1 argument2:(id)arg2 {
    return [[self alloc] initWithArgument1:arg1 argument2:arg2];
}

It's that simple.

Now instead of:

MyClass *obj = [[MyClass alloc] initWithArgument1:foo argument2:bar];

We can write simply:

MyClass *obj = [MyClass myClassWithArgument1:foo argument2:bar];

Upvotes: 4

Mario
Mario

Reputation: 4520

It's called a convenience initialiser. These class methods hand an initialised and configured object back to you. In their implementation, they themselves do the alloc/init part. Google up on it and you will find many examples.

Upvotes: 1

Related Questions