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!
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With