We all use factory methods, a.k.a. convenience methods. We often write them ourselves. But there’s a wrong way, and a right way, to write a factory method for your Objective-C class. Do it wrong, and you cut off some features of Objective-C. Do it right, and you open yourself up to new object-oriented possibilities.
Let’s back up and review what we mean by a factory method. This is a convenience method that you invoke on a class to say, “Make me one of your kind.” (Some folks call this a “convenience constructor” which is odd to me, because the underlying mechanics are quite different from Java or C++.)
Factory method: The wrong way
Let’s say we have a simple class:
@interface Foo : NSObject
To create an autoreleased Foo object, we’d write
Foo *aFoo = [[[Foo alloc] init] autorelease];
But if you do this a lot, it becomes tedious and can clutter your code. So let’s create a factory method.
At this point, it’s tempting to copy and paste into the body of the new method:
+ (Foo *)foo
return [[[Foo alloc] init] autorelease];
Looks fine. Everything works. So what’s the problem? Continue Reading…