1

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?

Community
  • 1
  • 1
A O
  • 5,516
  • 3
  • 33
  • 68
  • I would call the `initWithProperty` method the "convenience initializer", and the `someClassWithProperty` method the "factory method". But that's just based on general knowledge. I don't recall seeing either term being used in the Apple docs. – user3386109 Sep 21 '15 at 17:58
  • Yeah I can't find anything concrete in the docs. A lot of sources have conflicting information-- which is why I want to say the terms are interchangable – A O Sep 21 '15 at 18:01
  • Yup, that's the way the English language works. A word means whatever you want it to mean, as long as other people agree with your definition :) – user3386109 Sep 21 '15 at 18:07
  • Haha well when I was committing a change, I wasn't sure which term to put in the commit message. I want to be consistent with other people's definition. Also if I read one or the other, I want to make sure I know exactly what they're talking about – A O Sep 21 '15 at 18:09

1 Answers1

3

"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:

Community
  • 1
  • 1
jscs
  • 63,694
  • 13
  • 151
  • 195
  • Thanks Josh, so in your ObjC do you prefer instantiating objects w/ a factory method or a designated initializer? – A O Sep 21 '15 at 18:26
  • Personally, under ARC, I almost always write a convenience constructor. – jscs Sep 21 '15 at 18:31