valueForKeyPath returning nil unexpectedly

512 views Asked by At

This is a fairly short question, but I'm a bit confused on how to fix it.

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.
}

I'm a bit confused on why this is happening. How come valueForKeyPath is returning nil when the above is returning a value? I'm calling this on an NSDictionary.

This is the log I'm getting:

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

Here's how I'm declaring datesSectionHeader:

extension NSDictionary {

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

There are 1 answers

0
Ken Thomases On BEST ANSWER

NSDictionary modifies the standard behavior of Key-Value Coding so that it accesses the dictionary's contents rather than its properties. It does this by overriding value(forKey:) (which is, in turn, used by value(forKeyPath:)).

As documented, its override of value(forKey:) checks if the key is prefixed by "@". If it's not, it returns the result of object(forKey:), accessing the dictionary contents. If it is prefixed with "@", it strips the "@" and returns the result from the superclass's implementation, which accesses the dictionary's properties.

So, in this particular case, you can access the results from your datesSectionHeader() getter method using the following:

item.value(forKeyPath: "@datesSectionHeader")