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;
有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top