valueForKeyPath 意外返回 nil

valueForKeyPath returning nil unexpectedly

这是一个相当简短的问题,但我对如何解决它有点困惑。

for item in filteredAndSortedDates {
     print(item.datesSectionHeader()) // Returns a value
     print(item.value(forKeyPath: "datesSectionHeader") as Any) // Returns nil
     // The "as Any" part up above is just to keep the compiler quiet. It doesn't have any meaning as this is just for testing purposes.
}

我有点困惑为什么会这样。为什么 valueForKeyPath 在返回值时返回 nil ?我在 NSDictionary.

上调用它

这是我得到的日志:

HAPPENING THIS WEEK
nil
HAPPENING THIS WEEK
nil
HAPPENING THIS WEEK
nil
HAPPENING WITHIN A YEAR
nil

这是我声明的方式 datesSectionHeader:

extension NSDictionary {

     // FIXME
     func datesSectionHeader() -> String {
         // Doing some work in here.
     }
}

NSDictionary 修改键值编码的标准行为,以便它访问字典的内容而不是其属性。它通过覆盖 value(forKey:)(反过来由 value(forKeyPath:) 使用)来实现。

documented 一样,它对 value(forKey:) 的覆盖检查键是否以“@”为前缀。如果不是,它 returns object(forKey:) 的结果,访问字典内容。如果它以“@”为前缀,它会去除“@”和returns来自超类实现的结果,它访问字典的属性。

因此,在这种特殊情况下,您可以使用以下方法访问 datesSectionHeader() getter 方法的结果:

item.value(forKeyPath: "@datesSectionHeader")