ios developer tiny share-20161009

来源:互联网 发布:xp系统无法连接网络 编辑:程序博客网 时间:2024/04/29 14:03

今天讲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.

0 0
原创粉丝点击