Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of using a factory method in objective-c context? [closed]

What is the purpose of use of a factory method in objective-c context?

I am a bit confused about the use of factory methods in objective-c? What is the usefulness of doing so?

What is an example of using factory method in objective-c?

A bit confused. Any explanation would help!

like image 679
Kermit the Frog Avatar asked Oct 18 '13 13:10

Kermit the Frog


1 Answers

Objective-C does not have constructor methods that are available in other programming languages. Factory methods are essentially Objective C's constructor methods. They allow you to allocate memory for your object and initialize the values.

In your class, add methods with this pattern:

//Please follow Obj C naming conventions and name all init 
//methods "initWith" then desc
-(id)initWithString:(NSString*)str {
    if(self = [super init]) {
        _someProperty = str;
        _someOtherProperty = 0;
    } return self;
}

//Please follow Obj C naming conventions and name all factory 
//methods "myClassWith" then desc
+(instancetype)someClassWithString:(NSString*)str {
    return [[self alloc] initWithString: str];
}

//Pretty much every factory method should have a matching init method, and 
//only one init method should actually do the if(self = [super init] { /*do
//stuff*/ } return self;, the other init methods should call this one in some
//form or fashion

Then in main, you can do:

SomeClass *myVariableName = [SomeClass someClassWithString: 
    @"Init with me please"];

It saves you from having to do this:

SomeClass *myVariableName = [[SomeClass alloc] initWithString: 
    @"Init with me please"];

Or this:

SomeClass *myVariableName = [[SomeClass alloc] init];
[myVariableName mySetterMethod: @"Init with me please"];
[myVariableName setThatOtherProperty: 0];
like image 173
nhgrif Avatar answered Oct 12 '22 03:10

nhgrif