3

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;
Eimantas
  • 48,927
  • 17
  • 132
  • 168
  • you can refer http://stackoverflow.com/questions/4702904/what-is-preferable-in-objective-c-id-or-explicit-type – Maulik Sep 01 '11 at 09:26

1 Answers1

1

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.

Kevlar
  • 8,804
  • 9
  • 55
  • 81
  • How am I leaking the internal information when not using `id`? The `NSLog` statement would show the private class's name that is returned by public class's initializer. – Eimantas Sep 09 '11 at 04:58
  • 2
    Right, but that is only discoverable at runtime. If your method signatures include the (presumably private) subclass type in them, clients of your API might reference those types directly, which negates the benefits of having an opaque superclass whose purpose is to hide the implementation details of your class hierarchy. – Kevlar Sep 15 '11 at 17:53