今天讲Objective-C使用protocol隐藏实现。
Protocols Are Used for Anonymity
Protocols are also useful in situations where the class of an object isn’t known, or needs to stay hidden.
As an example, the developer of a framework may choose not to publish the interface for one of the classes within the framework. Because the class name isn’t known, it’s not possible for a user of the framework to create an instance of that class directly.
Instead, some other object in the framework would typically be designated to return a ready-made instance, like this:
id utility = [frameworkObject anonymousUtility];In order for this anonymousUtility object to be useful, the developer of the framework can publish a protocol that reveals some of its methods. Even though the original class interface isn’t provided, which means the class stays anonymous, the object can still be used in a limited way:
id <XYZFrameworkUtility> utility = [frameworkObject anonymousUtility];If you’re writing an iOS app that uses the Core Data framework, for example, you’ll likely run into the NSFetchedResultsController class. This class is designed to help a data source object supply stored data to an iOS UITableView, making it easy to provide information like the number of rows.
If you’re working with a table view whose content is split into multiple sections, you can also ask a fetched results controller for the relevant section information. Rather than returning a specific class containing this section information, the NSFetchedResultsController class instead returns an anonymous object, which conforms to the NSFetchedResultsSectionInfo protocol. This means it’s still possible to query the object for the information you need, such as the number of rows in a section:
NSInteger sectionNumber = ...
id <NSFetchedResultsSectionInfo> sectionInfo =
[self.fetchedResultsController.sections objectAtIndex:sectionNumber];
NSInteger numberOfRowsInSection = [sectionInfo numberOfObjects];Even though you don’t know the class of the sectionInfo object, the NSFetchedResultsSectionInfo protocol dictates that it can respond to the numberOfObjects message.
本文探讨了Objective-C中如何利用协议来隐藏类的具体实现细节。通过框架开发者不公开类接口而仅公布协议的方式,使得外部使用者可以有限地利用这些匿名对象,同时保持了类的内部实现不被暴露。
2421

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



