获取共享 Objective-C 方法中的类类型?
在 Objective-C 中有 Alloc/Init 比喻。他们还添加了一个名为“new”的共享便利方法,该方法在内部仅连续调用这两个方法。如果我创建一个名为 FooClass 的 NSObject 子类,FooClass 就会选择这些共享方法,包括“new”。
但是...到底是如何实现的?
它不能简单地委托给基类,因为这只会实例化 NSObject 的实例,而不是派生类 FooClass,但它仍然有效!那么有人会如何写类似的东西呢?
换句话说,基类不应该是这个...
+ (id) somethingLikeNew{
return [[NSObject alloc] init];
}
而是这个
+ (id) somethingLikeNew{
return [[<SomethingThatMapsToFooClassType> alloc] init];
}
......其中'SomethingThatMapsToFooClassType'是继承自NSObject的派生类的类型,并且需要拾取共享方法'somethingLikeNew '。
基本上,我添加了 NSObject 的类别,并且我共享了需要知道类型的方法,但实现都是通用的,因此进入 NSObject 上的类别,而不是在我的类文件中的所有地方(同样的方式你并没有到处都是“新的”。)
有人吗?布勒?布勒?
中号
In Objective-C there is the Alloc/Init metaphor. They've also added a shared convenience method called 'new' that internally just calls both in succession. And if I create a subclass of NSObject called FooClass, FooClass picks up those shared methods, including 'new'.
BUT... how the heck is that implemented??
It can't simply delegate to the base class because that would just instantiate an instance of NSObject, not your derived class FooClass, yet it still works! So how would someone write something similar?
In other words, the base class shouldn't be this...
+ (id) somethingLikeNew{
return [[NSObject alloc] init];
}
But rather this...
+ (id) somethingLikeNew{
return [[<SomethingThatMapsToFooClassType> alloc] init];
}
...where 'SomethingThatMapsToFooClassType' is the type of the derived class that inherits from NSObject and which needs to pick up the shared method 'somethingLikeNew'.
Basically I'm adding a category off of NSObject and I have shared methods that need to know the type, but the implementations are all generic, hence going in a category on NSObject and not all over the place in my class files (the same way you don't have 'new' all over the place. It's just there.)
Anyone? Bueller? Bueller?
M
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在任何 Objective-C 方法中,
self
(隐式)参数指的是接收者。对于类方法,self
是Class
对象。所以多态类方法可以像这样实现Within any Objective-C method, the
self
(implicit) parameter refers to the receiver. In the case of a class method,self
is theClass
object. So polymorphic class methods can be implemented like哈!发布此内容后两秒钟我自己发现了!您可以在共享方法中使用“self”来表示派生类的类类型,因此上面的内容很简单......
该死,这太简单了!希望这对其他人有帮助!
中号
Ha! Found it myself two seconds after posting this! You can use 'self' in a shared method to represent the class type for the derived class, so the above would simply be...
Damn, that was easy! Hope this helps someone else!
M