In Object-C, Protocol is used to define a group of attributes and Methods independent of a specific class. It does not implement these methods. Any class can implement Protocol, protocol can inherit another Protocol. In terms of features, Protocol functions similar to interfaces in the Java World.
Protocol basically adopts the "Delegation" mode in the specific use process, that is, the Protocol definition method is used, and then different classes use different implementations to complete the polymorphism of a behavior. This Delegate mode is widely used in iOS SDK class libraries. For example, UITableViewDataSource defines a series of methods for using the data source in Table View. When developers need to use Table View, you need to implement this series of methods, and then give the defined Table View delegate to the current object. In this way, Table views on different interfaces can be displayed based on their own object implementations.
Defining protocol is very simple, as follows:
Object-c code
- @protocol MyProtocol <NSObject>
- // pst of methods and properties
- [url=home.php?mod=space&uid=10695]@END[/url]
In addition, protocol also supports two keywords: @ required and @ optional. As the name implies: all methods after @ required must implement the protocol class, and the methods after optional can not. By default, all methods and attributes are @ required.
Object-c code
- @protocol MyProtocol <NSObject>
- // pst of methods and properties
- @required
- // pst of methods and properties
- @optional
- // pst of methods and properties
- @end
In addition, protocol can inherit another protocol.
Object-c code
- @protocol A
- -(void)methodA;
- @end
- @protocol B <A>
- -(void)methodB;
- @end
Protocol implementation is also very simple. In Object-C, if a class uses a protocol, you only need to add '<ProtocolName,...>' to the class definition.
Object-c code
- @interface MyClass : NSObject <MyProtocol, AnotherProtocol, YetAnotherProtocol>
- ...
- <A href="mailto:.@end">@end</A>
Finally, like interfaces in Java, once an object implements a protocol, you can use the protocol pointer to point to the object. This is why when the current object implements UITableViewDataSource protocol, you can assign the delegate value of Table View to the current object. In the UITableView code, the dataSource attribute definition looks like this.
- Object-c code
- ....
- Id <UITableViewDataSource> _ dataSource;
- & Helpp;