Detailed explanation of the role of interface and protocol in objective-c
In the past, the role of interface in Objective-C, i.e. header files, has not been very clear. I have read some articles recently, and combined with my own experiments, I have a little understanding of the role of header files.
In my opinion, the function of the header file is to define external interfaces.
However, this is the only thing it does. The header file cannot guarantee that the external interface will be implemented.
According to whether the .h file defines a method and whether the .m file implements a method, it can be divided into three categories:
The first category is the .h file definition method, and the .m file also implements the method, this is the most common method and the most problematic method.
The second category is the .h file definition method, but the .m file does not implement this method. At this time, the @implementaion code of the .m file will prompt "imcomplete implementation", which means that the methods and variables defined by the header file are not fully implemented.
For example: The definition in the .h file is as follows:
@interface Test : NSObject{} -(void)hello; @end
But this method is not implemented in the .m file. Externally, we can call this method, it has no problem at compile time, but there will be an "unrecognized selector sent to instance" error at runtime.
The third category is that the .h file is not defined, but this method is found in the .m file.
For example, implement this in the .m file:
#import "" @implementation Test -(void)hello{ NSLog(@"hello world!"); } @end
At this time, the function hello() is equivalent to a private function. We can only call it with [self hello] in the class, but not externally.
Therefore, I think that the header file in objective-c is just for the sake of more convenient compilation, and it is not a real interface.
Relatively speaking, protocol is considered a real interface, and its meaning is similar to that of interfaces in Java.
The protocol method is divided into two types: one is necessary to implement, and the other is not necessarily implemented. The methods that are not necessarily implemented are actually similar to those defined in the .h file. And the method that must be implemented is more useful.
We can use this method to initialize a class that implements a protocol called Hello:
id<Hello> test = [[Test alloc] init];
In addition to its function as an interface, protocol is often used as a method for interacting between classes. At this time, it is called delegate. The main function of delegate is to make part of what one class needs to do and let another class complete it. There are so many articles introducing delegate online, and I won’t talk about it here.
Thank you for reading, I hope it can help you. Thank you for your support for this site!