I have an array which contains items of NSDictionary, I want to transform the items to other objects, my first thought is valueForKey:, so I add a category method toMyObject for NSDictionary, and call for:
[array valueForKey:@"toMyObject"]
But it doesn’t work as expect, it just returns the array of NSNulls.
Any ideas to solve this problem if I don’t want to enumerate the array?
Answer to myself. The
valueForKey:of dictionary overwrite the default behavior, if the dictionary doesn’t have the key, it will return nil and not call the accessor method asNSObjectdo, as Apple document says:Since
NSDictionaryis a cluster class, it’s not recommend to subclass to overwrite the behavior. Instead I use the method swiss like this:Now it’s safe for an NSArray to call
valueForKey:@"toMyObject".