Objective-C basics: protocol (@ protocol)
C ++ Defines abstract interfaces with pure virtual functions. classes that inherit abstract interfaces must implement pure virtual functions of all parent classes. The protocols in OC are similar to pure virtual functions in C ++. 1. Declare the agreement. @ Protocol is followed by the protocol name. @ Protocol NSObject @ end if a protocol inherits from another protocol, fill in the parent protocol name in brackets as the declaration method. @ Protocol SonProtocol <BaseProtocol> @ end 2. The class conforms to a certain protocol. Fill in the protocol name with Angle brackets in the class declaration. @ Interface Car: NSObject <NSCopying> @ end @ interface Car: NSObject <NSCopying, NSCoding> @ end 3. the Protocol method declaration can use @ optional and @ require to indicate whether the classes that comply with the Protocol must implement the methods in the Protocol. @ Require is required, and @ optional is optional. Unlike C ++, C ++ must implement all pure virtual interfaces. @ Protocol WorkerProtocol <NSObject> @ optional-(void) doSomeOptionalWork; @ required-(void) doSomeRequiredWork; @ end the code above indicates that classes conforming to the WorkerProtocol must implement dosomerequired, doSomeOptionalWork is optional. 4. You can explicitly specify in the method parameters and instance variables that the object must comply with a certain protocol. @ Interface Manager: NSObject @ property (weak) id <WorkerProtocol> delegate;-(void) doWork; @ end the code above indicates that delegate must comply with the WorkerProtocol. If not, the compiler will warn. The following code will warn the compiler of Assigning to 'id <WorkerProtocol> 'from incompatible type 'nsstring * _ strong' NSString * name = @ "akon"; manager. delegate = name; [manager doWork];