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?
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];