ios - 请帮助没有意义的协议(protocol)代码

标签 ios objective-c cocoa

我被这个陈述的一部分难住了:

@property(nonatomic, readonly) NSArray <id<NSFetchedResultsSectionInfo>>*sections

这个属性属于 NSFetchedResultsController 类。 虽然 NSFetchedResultsSectionInfo 是一个协议(protocol),id<NSFetchedResultsSectionInfo>是一个必须符合 NSFetchedResultsSectionInfo 协议(protocol)的对象类型。 id<NSFetchedResultsSectionInfo>不是协议(protocol),因此将它们括在尖括号中 <id<NSFetchedResultsSectionInfo>>没有意义。 语句 NSArray <id<NSFetchedResultsSectionInfo>>对我来说没有意义,因为您如何使对象类型 id 成为 NSArray 类的协议(protocol)。有人可以阐明这一点吗?谢谢。

最佳答案

该语法实际上并不意味着该数组符合任何协议(protocol)。该符号具有误导性。它只告诉您数组内部的值是id 并且符合NSFetchedResultsSectionInfo 协议(protocol)。

documentation状态:

The objects in the sections array implement the NSFetchedResultsSectionInfo protocol.

您需要确保它只包含指定类型的值,如果您这样做,编译器会告诉您您正在尝试插入不兼容的对象。

您可能想看一下本 apple doc 的最后一节.

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.

关于ios - 请帮助没有意义的协议(protocol)代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30873650/

相关文章:

ios - 使用 XIB 的自定义 NSView/UIView 子类?

ios - 如何快速将日期、月份和年份转换为毫秒

objective-c - 搜索模板 tvOS

ios - UIActivityViewController 没有将换行符传递给某些事件

ios - Swift 3.0 中的结构枚举

iphone - Obj-c,释放对象的校验和不正确 - 对象可能在释放后被修改

ios - 将容器置于其他容器之上

swift - 初始化需要 `init(coder: NSCoder)`的子类

objective-c - 在 Mac OS X 下知道手指在触控板上的位置

objective-c - 通过组合两个 NSDate 来创建一个新的 NSDate