Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

objective-c

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 protocol 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.

like image 570
Tneuktippa Avatar asked Jun 21 '11 21:06

Tneuktippa


People also ask

What's the difference between a protocol and a class in Swift?

You can create objects from classes, whereas protocols are just type definitions. Try to think of protocols as being abstract definitions, whereas classes and structs are real things you can create.

What is a protocol in iOS?

In iOS development, a protocol is a set of methods and properties that encapsulates a unit of functionality. The protocol doesn't actually contain any of the implementation for these things; it merely defines the required elements.


3 Answers

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.

like image 137
ughoavgfhw Avatar answered Oct 03 '22 18:10

ughoavgfhw


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

enter image description here

like image 44
Andrey Chernukha Avatar answered Oct 03 '22 19:10

Andrey Chernukha


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.

like image 44
FreeAsInBeer Avatar answered Oct 03 '22 19:10

FreeAsInBeer