今天讲Cocoa and Cocoa Touch Define a Large Number of Protocols。
Cocoa and Cocoa Touch Define a Large Number of Protocols
Protocols are used by Cocoa and Cocoa Touch objects for a variety of different situations. For example, the table view classes (NSTableView for OS X and UITableView for iOS) both use a data source object to supply them with the necessary information. Both define their own data source protocol, which is used in much the same way as the XYZPieChartViewDataSource protocol example above. Both table view classes also allow you to set a delegate object, which again must conform to the relevant NSTableViewDelegate or UITableViewDelegate protocol. The delegate is responsible for dealing with user interactions, or customizing the display of certain entries.
Some protocols are used to indicate non-hierarchical similarities between classes. Rather than being linked to specific class requirements, some protocols instead relate to more general Cocoa or Cocoa Touch communication mechanisms that may be adopted by multiple, unrelated classes.
For example, many framework model objects (such as the collection classes like NSArray and NSDictionary) support the NSCoding protocol, which means they can encode and decode their properties for archival or distribution as raw data. NSCoding makes it relatively easy to write entire object graphs to disk, provided every object within the graph adopts the protocol.
A few Objective-C language-level features also rely on protocols. In order to use fast enumeration, for example, a collection must adopt the NSFastEnumeration protocol, as described in Fast Enumeration Makes It Easy to Enumerate a Collection. Additionally, some objects can be copied, such as when using a property with a copy attribute as described in Copy Properties Maintain Their Own Copies. Any object you try to copy must adopt the NSCopying protocol, otherwise you’ll get a runtime exception.
本文探讨了Cocoa和CocoaTouch框架中协议的应用,包括数据源和代理模式的具体实现方式,以及如何利用NSCoding进行对象归档。此外还介绍了NSFastEnumeration和NSCopying等协议的作用。
233

被折叠的 条评论
为什么被折叠?



