Protocol-Protocol
The protocol is used to define the attributes, behaviors, and callbacks of objects.
There are two keywords in the Protocol: @ private and @ optional. @ private indicates the method that must be written to use this protocol, and @ optional indicates the optional method. If not, you can leave it empty.
Like uitableview, it has two Protocols: uitableviewdelegate and uitableviewdatasource. uitableviewdelegate specifies action operations, and the methods in it are optional.
Uitableviewdatasource specifies the data storage structure. There are two required methods. Therefore, you must define these two methods when implementing uitableviewdatasource. Otherwise, an error occurs in the program.
If you use a response class or control, if the class defines the protocol, you can implement the Protocol as needed.
Similar to interfaces in Java, protocol is a part of objective-C syntax.
Define protocol as follows
@protocol ClassADelegate - (void)methodA;- (void)methodB; @end
A group of functions are defined. These functions are called a Protocol together, that is, the protocol.
The function must be implemented.
@interface ClassB <ClassADelegate> {}@end
It is called classb conform to Protocol classadelegate, that is, classb implements this protocol,
That is, this group of functions is implemented.
With the header file above, we can call it with confidence.
ClassB *b = [[ClassB alloc] init];[b methodA];[b methodB];
You don't have to worry about the unrecognized selector sent to instance error.
Therefore, protocol is a set of function definitions that are separated from class declarations.
id<ClassADelegate> b = ...;[b methodA];
This usage is also common. B is an ID type, which knows the IMPLEMENTATION OF THE classadelegate group function.
Delegate -- delegate, proxy
Applicable scenarios:Class A calls class B. delegate is used when class B wants to call the method of Class.
To understand the following code, you must know the protocal file: classa. h # import <Foundation/Foundation. h> # import "classb. H "@ interface classa: nsobject <sampleprotocal>-(void) test; @ end file: classa. M # import "classa. H "@ implementation classa-(void) test {classb * classb = [[classb alloc] init]; classb. delegate = self; [classb actionofclassb];}-(void) callback {nslog (@ "this method will be called by Class B");} @ end file: classb. h # import <Foundation/Foundation. h >@protocol sampleprotocal <nsobject> @ required-(void) callback; @ end @ interface classb: nsobject {id <sampleprotocal> delegate;} @ property (nonatomic, retain) ID <sampleprotocal> delegate;-(void) actionofclassb; @ end file: classb. M # import "classb. H "@ implementation classb @ synthesize delegate;-(void) actionofclassb {[Delegate callback];} @ end