super 中的方法无论如何都会被子类化 (Cocoa)
抱歉,如果这是转发,但我无法完全搜索它,因为我无法用几句话解释它。我有一个包含很多方法的超类,但它们总是(不是全部)被子类化。我需要从超级运行这些方法。我可以将 super 中的方法保留为空,或者我可以不在 super 中键入它们,但无论如何都可以调用它们,就像 [self myMethod]
一样,它会调用我的子类方法,即使它不存在于极好的。这可行,但 Xcode 给了我一个错误。 'superclass' 可能不会响应 '-subclassmethod'
我应该怎么做才能不会收到警告?
Sorry if this is a repost but I couldn't quite search for it because I can't explain it in a few words. I have a super class with lots of methods but they will always (not all of them) be subclassed. From the super I need to run those methods. I could either leave the methods in super empty or I could just not type them in super but call them anyway like so [self myMethod]
and it will call my subclassed method even if it doesn't exist in super. This works but Xcode gives me an error though. 'superclass' may not respond to '-subclassmethod'
What should I do so I won't get the warnings?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我更喜欢像这样在超类中定义未实现的方法:
这几乎完全是多余的,因为如果我根本没有定义该方法,Objective-C 运行时最终会调用
-doesNotRecognizeSelector:
。但因为我确实定义了它,所以它位于类的接口中,这既使编译器满意,又为我提供了一些文档。I prefer to define the unimplemented methods in the superclass like this:
It's almost entirely redundant, because the Objective-C runtime would eventually call
-doesNotRecognizeSelector:
if I didn't define the method at all. But because I do define it, it's in the class's interface which both keeps the compiler happy and provides me with some documentation.您可以在 协议,其他语言中称为“接口”。
更改变量的类型声明以声明该对象符合协议。
请注意,您将无法将 SuperClass 的实例传递给
doStuffWith:and:
,因为它不会实现 MyProtocol,但听起来这就是您想要的。Rather than the superclass, you could declare the methods in a protocol, what is called a "interface" in other languages.
Change the type declaration of the variables to declare that the object conforms to the protocol.
Note that you won't be able to pass an instance of your SuperClass to
doStuffWith:and:
, since it won't implement MyProtocol, but it sounds like that's what you want.我的解决方案有点奇怪,但它是:
在
NSObject
中拥有与类同名的协议。因为正式协议中的方法默认为@required
,所以您将在两端受到保护:在编译时中,如果您的JSDog
子类声称符合
,但未实现-yipe
,您将收到错误;在运行时,如果您的子类未声明符合
,则在实例化子类时您将收到警告。My solution was a little weird, but here it is:
Having a protocol with the same name as a class is precedented in
NSObject
. Because methods in a formal protocol a by default@required
, you will be protected on both ends: in compile-time, if yourJSDog
subclass purports to conform to<JSDog>
, but doesn't implement-yipe
, you will receive an error; at runtime, if your subclass does not claim to conform with<JSDog>
, you will receive a warning when the subclass is instantiated.我最近喜欢使用 NSAssert 来完成此任务:
I lately like using NSAssert for this task: