ios developer tiny share-20161009

本文探讨了Objective-C中如何利用协议来隐藏类的具体实现细节。通过框架开发者不公开类接口而仅公布协议的方式,使得外部使用者可以有限地利用这些匿名对象,同时保持了类的内部实现不被暴露。

今天讲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.
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值