ios developer tiny share-20160927

来源:互联网 发布:淘宝网商城食品香外香 编辑:程序博客网 时间:2024/06/10 15:51

今天继续讲Objective-C的protocol,讲“Protocols Define Messaging Contracts”。


Protocols Define Messaging Contracts

A class interface declares the methods and properties associated with that class. A protocol, by contrast, is used to declare methods and properties that are independent of any specific class.

The basic syntax to define a protocol looks like this:

@protocol ProtocolName// list of methods and properties@end

Protocols can include declarations for both instance methods and class methods, as well as properties.

As an example, consider a custom view class that is used to display a pie chart, as shown in Figure 5-1.

Figure 5-1  A Custom Pie Chart View


To make the view as reusable as possible, all decisions about the information should be left to another object, a data source. This means that multiple instances of the same view class could display different information just by communicating with different sources.

The minimum information needed by the pie chart view includes the number of segments, the relative size of each segment, and the title of each segment. The pie chart’s data source protocol, therefore, might look like this:

@protocol XYZPieChartViewDataSource- (NSUInteger)numberOfSegments;- (CGFloat)sizeOfSegmentAtIndex:(NSUInteger)segmentIndex;- (NSString *)titleForSegmentAtIndex:(NSUInteger)segmentIndex;@end

Note: This protocol uses the NSUInteger value for unsigned integer scalar values. This type is discussed in more detail in the next chapter.
The pie chart view class interface would need a property to keep track of the data source object. This object could be of any class, so the basic property type will be id. The only thing that is known about the object is that it conforms to the relevant protocol.

The syntax to declare the data source property for the view would look like this:

@interface XYZPieChartView : UIView@property (weak) id <XYZPieChartViewDataSource> dataSource;...@end

Objective-C uses angle brackets to indicate conformance to a protocol. This example declares a weak property for a generic object pointer that conforms to the XYZPieChartViewDataSource protocol.

Note: Delegate and data source properties are usually marked as weak for the object graph management reasons described earlier, inAvoid Strong Reference Cycles.


By specifying the required protocol conformance on the property, you’ll get a compiler warning if you attempt to set the property to an object that doesn’t conform to the protocol, even though the basic property class type is generic. It doesn’t matter whether the object is an instance of UIViewController or NSObject. All that matters is that it conforms to the protocol, which means the pie chart view knows it can request the information it needs.

0 0
原创粉丝点击