If certain methods are defined in a protocol, and a class implements the protocol, the class must implement these methods. In other words, the protocol is a common set of method declarations, who implement the Protocol, who is responsible for implementing these methods, or there will be a yellow warning. The protocol can extend an existing protocol. The keyword for the agreement is protocol, starting with @protocol and ending with @end. When implementing a protocol in a class, you only need to add a < protocol name after the class name; Here's a look at the code:
Define a protocol first: Eat.h
[Plain]View Plaincopy
- #import <Foundation/Foundation.h>
- @protocol eat <nsobject>//protocol eat extended the protocol NSObject.h
- -(void) eat;
- @end
The above extended NSObject protocol is not implemented, because the class inheriting from NSObject has inherited the implementation of the NSObject protocol
Create a class below: Human.h
[Plain]View Plaincopy
- #import <Foundation/Foundation.h>
- #import "Eat.h"
- @interface Human:nsobject <eat>
- @end
Human.m
[Plain]View Plaincopy
- #import "Human.h"
- @implementation Human
- -(void) Eat
- {
- NSLog (@ "eat defined in the agreement");
- }
- @end
Called in MAIN.M:
[Plain]View Plaincopy
- #import <Foundation/Foundation.h>
- #import "Eat.h"
- #import "Human.h"
- int main (int argc, const char * argv[])
- {
- @autoreleasepool {
- Human *human =[[human alloc] init];
- [Human eat];
- }
- return 0;
- }
2012-03-18 14:35:29.099 category1[1752:403] defined in the agreement. Eat
Very simple, in addition, in the new version of the Objective-c, added some options for the protocol, @optional, @required, the protocol must be implemented in the method, otherwise it will be error, but if the @optional modified, there is no such restriction, The method that must be implemented by default is equivalent to a @required modification, such as the above code, and we can make the following changes:
Eat.h
[Plain]View Plaincopy
- #import <Foundation/Foundation.h>
- @protocol eat <nsobject>//protocol eat extended the protocol NSObject.h
- -(void) eat;
- @optional
- -(void) Playguitar;
- @required
- -(void) sleep;
- @end
In this case, the sleep method and the Eat method must also be implemented, and the Playguitar method is optional.
Use of iOS Information interaction Protocol