Objective-C 类簇和私有类初始值设定项
通常,作为一个好的 Cocoa 公民,我编写返回类型 id 的初始化程序(即指向泛型对象的指针),以便以后更容易进行子类化(尽管 99% 的时间我不需要这样做)。
现在我正在创建自己的类集群(许多私有类以单个公共类为上限)。问题:我是否仍然需要将私有类的初始值设定项定义为返回通用 id
指针:
- (id)initSubclassForFooClassCluster;
或指向私有类本身的指针,例如:
- (SubclassForFooClassCluster *)initSubclassForFooClassCluster;
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在 init 方法中使用 (id) ,声明更具体的类型对您没有多大作用。如果你真的想让你的私有子类私有,你应该使用 id ,否则你就会将类内部的信息泄露给外界,而这些信息实际上并不需要,具体取决于你的需要。
NSString 是一个类簇,它的所有 init 方法都返回 id,因为同一个方法可能会返回不同的对象类型,具体取决于传递给 init 方法的内容。
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.