objective-cdesign-patternsabstract-factoryclass-cluster

Objective-C class clusters and private class initializers


Ordinarily, being a good Cocoa citizen, I write my initializers returning type id (i.e. pointer to generic object) for easier subclassing later (though 99% of time I do not need that).

Now I'm creating my own class cluster (lots of private classes capped with single public class). The question: Do I still need to define private classes' initializers as returning generic id pointer:

- (id)initSubclassForFooClassCluster;

or a pointer to the private class itself like:

- (SubclassForFooClassCluster *)initSubclassForFooClassCluster;

Solution

  • You can just use (id) in your init methods, declaring a more specific type won't do much for you. If you truly want to make your private subclasses private you should use id, otherwise you are leaking information of the internals of your class to the outside world when that information shouldn't really be necessary, depending on what you need.

    NSString is a class cluster, and all of its init methods return id, because the same method might return differing object types depending on what you pass to the init method.