开发者

Why is it NOT a compiler error to specify a protocol but not implement required methods?

In objective-c, I can do something like

@interface MyViewController : UIViewController <UITextInputDelegate>

to create the specification for a class MyViewController which implements the UITextInputDelegate protocol. Now, this p开发者_Python百科rotocol has several required methods, so I would think that the compiler would not let the code compile at all unless those methods did in fact have implementations in the .m file. Nonethless, this compiles. The compiler does spout warnings, so obviously it's detecting that I didn't implement the required methods, but I'm wondering why it makes sense to allow this to compile at all, on the part of the language designer.


You get a compiler error when the code can't be compiled. Not implementing a method doesn't prevent the code from being compiled because objective-c is a dynamic language. That means that the methods aren't directly linked, so their location doesn't need to be known at compile time. Warnings mean that there is something which could cause errors at runtime, but that the code successfully compiled.


If you want to turn this warning into an error then just add -Werror=protocol into Other Warning Flags in the Build Settings.

Why is it NOT a compiler error to specify a protocol but not implement required methods?


As ughoavgfhw pointed out, it's not an error because the dynamic nature of the language allows for those methods to be added at runtime. Just because the method isn't found at compile time doesn't mean it won't be there at run time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜