Please help protocol code that does not make sense
我被这句话的一部分难住了:
1
|
@property(nonatomic, readonly) NSArray <id<NSFetchedResultsSectionInfo>>*sections
|
这个属性属于 NSFetchedResultsController 类。
虽然 NSFetchedResultsSectionInfo 是一个协议,但 id<NSFetchedResultsSectionInfo> 是一个必须符合 NSFetchedResultsSectionInfo 协议的对象类型。 id<NSFetchedResultsSectionInfo> 不是协议,因此将它们括在尖括号中
<id<NSFetchedResultsSectionInfo>> 没有意义。
语句 NSArray <id<NSFetchedResultsSectionInfo>> 对我来说没有意义,因为你怎么能让对象类型 id 成为 NSArray 类的协议。有人可以对此有所了解吗?谢谢。
这种语法实际上并不意味着数组符合任何协议。该符号具有误导性。它只告诉你数组中的值是 id 并且符合 NSFetchedResultsSectionInfo 协议。
文档说明:
The objects in the sections array implement the NSFetchedResultsSectionInfo protocol.
您需要确保它只包含指定类型的值,并且如果您这样做,编译器会告诉您您正在尝试插入不兼容的对象。
你可能想看看这个苹果文档的最后一部分。
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
Even though you don’t know the class of the sectionInfo object, the NSFetchedResultsSectionInfo protocol dictates that it can respond to the numberOfObjects message.
- 感谢您的解释。我非常感谢。我认为 NSArray <id<NSFetchedResultsSectionInfo>>*sections 是我错过的一些新语法。顺便说一句,为什么苹果会写 @property(nonatomic, readonly) NSArray <id<NSFetchedResultsSectionInfo>>*sections 作为属性声明。它给人的印象是这确实是协议中的实际属性声明。
- 在协议声明中指出@property(nonatomic, readonly) NSArray *sections 并解释 NSArray 的对象是 id<NSFetchedResultsSectionInfo> 类型会不会更清楚。将所有内容放在一行中给人的印象是它是实际的声明。
- 有趣的。以前从来没有遇到过这个。
- @DonGiovanni 好吧,是的,您理解它可能更清晰。是的,但它不仅适用于您,也适用于编译器。也许他们应该选择不同的语法。如果你想知道为什么苹果会做出这样的决定,你必须和他们谈谈;)除了我在文档中能找到的东西,我什么都不知道。
来源:https://www.codenong.com/30873650/