A brief introduction to the protocol in Objective-C

A brief introduction to the role of protocol in one sentence: it is specifically used to declare some methods. A certain class that complies with this protocol is equivalent to having the declaration of all the methods in the protocol.

How to create:

Create a new OC file in Xcold, select the protocol type, enter the protocol name, click Create, and only create a .h file.

Syntax style:

@protocol sampleProtocol <NSObject>

@required
-(void)showFirstFunction;
-(void)showSecondFunction;

@optional
-(void)executeOptionalFunction;

@end

@protocol class : fatherClass <ptrotocol name>

// Write protocol function here...

@end

Description of @required and @optional:

If you add the @required modification, the method declared later must be implemented in the complying class.

If you add the @optional modification, the method declared later does not need to be implemented in the protocol class that complies with it. If you do not implement it, you will not receive a warning that it is not implemented.

However, even if the @required modification is added, it does not need to be implemented, but you will receive a warning. More application scenarios are in the process of multi-person collaborative development, prompting team members which methods must be implemented if they abide by this agreement, and which methods can be optionally implemented. The hint is more meaningful.

Regarding the observance and inheritance of the agreement

1. A class can comply with multiple protocols, syntax <procotolA, protocolB>

2. Protocols can inherit other protocols. Sub-protocols not only have their own methods, but also have the methods of the parent class.

3.NSObject is both a class name and a protocol name. The protocol name and class name can have the same name. Because NSBbject complies with the <NSObject> protocol, all methods in this protocol are owned by all OC objects.

other instructions:

If you want a pointer type to comply with a certain protocol, you can write:

NSString<protocolA> *string = [XXX new];

If the created object does not comply with this protocol, you will receive a warning. Avoid that the object does not comply with the protocol or does not implement the methods in the protocol.

Guess you like

Origin blog.csdn.net/JustinZYP/article/details/124186717