A O
A O

Reputation: 5698

In Objective-C, what is the difference between a Factory Method and a Convenience Initializer?

So every object has the default initializer method, -init

If you need your object to be instantiated with properties, you would write something like
-initWithProperty1:(Property1*)prop1 andProperty2:(Property2*)prop2

This would be called like this:
[[SomeClass alloc]initWithProperty1:(Property1*)prop1 andProperty2:(Property2*)prop2]

I always thought this was called a factory method (is that correct?)

But then I stumbled across this SO question: How to write an Objective-C convenience constructor

Where it looks like a "convenience constructor" is the same thing as a factory method? But maybe a convenience constructor specifically uses a class method as the initializer? so it seems like a convenience constructor would look like this:
+someClassWithProperty1:(Property1*)prop1 andProperty2:(Property2*)prop2 and would be called like:
[SomeClass someClassWithProperty1:(Property1*)prop1 andProperty2:(Property2*)prop2];

Does anybody know what the terminology should actually be? Are the two terms, "Factory Method" and "Convenience Constructor" the same thing in this context?

Upvotes: 1

Views: 198

Answers (1)

jscs
jscs

Reputation: 64022

"Convenience constructor" used to be the official term that Apple used for this concept; then they started calling it a "factory method". The nature of it hasn't changed: it's a class method that creates an instance. initWith... is not a factory method.

"Convenience initializer" is a term from Swift, not ObjC.

The "designated initializer" is unrelated except insofar as this creation method, like any other*, must eventually call through to it.


*With the exception of initWithCoder:

Upvotes: 3

Related Questions