-[NSObject valueForKey:] does not find methods which are added at runtime
| Originator: | gwendal.roue | ||
| Number: | rdar://18131778 | Date Originated: | 26/08/2014 |
| Status: | Open | Resolved: | |
| Product: | OSX | Product Version: | 10.9.4 |
| Classification: | Reproducible: | Always |
Summary:
The first step in the -[NSObject valueForKey:] search pattern is, as documented by https://developer.apple.com/library/mac/documentation/cocoa/conceptual/KeyValueCoding/Articles/SearchImplementation.html :
> 1. Searches the class of the receiver for an accessor method whose name matches the pattern get<Key>, <key>, or is<Key>, in that order. If such a method is found it is invoked.
A method which is added with `class_addMethod` should be found by `valueForKey:`. It is not.
Steps to Reproduce:
Run the following code:
NSString *nameIMP(id self, SEL _cmd) {
return @"name";
}
@interface ExtendedClass : NSObject
@end
@implementation ExtendedClass
@end
int main(int argc, const char * argv[])
{
@autoreleasepool {
class_addMethod([ExtendedClass class], @selector(name), (IMP)nameIMP, "v@");
id object = [[ExtendedClass alloc] init];
@try {
[object name];
NSLog(@"[object name] success.");
}
@catch (NSException *exception) {
NSLog(@"[object name] failure.");
}
@try {
[object valueForKey:@"name"];
NSLog(@"[object valueForKey:@\"name\"] success.");
}
@catch (NSException *exception) {
NSLog(@"[object valueForKey:@\"name\"] failure.");
}
}
return 0;
}
Expected Results:
The following lines appear in the log:
[object name] success
[object valueForKey:@"name"] success
Actual Results:
The following lines appear in the log:
[object name] success
[object valueForKey:@"name"] failure
Version:
OSX 10.9.4 (13E28).
Notes:
Configuration:
This bug appears, at least, with code compiled by Xcode 5.1.1 (5B1008) on an iMac14,2 running OSX 10.9.4 (13E28).
Comments
Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!
Apple Developer Relations answer
Engineering has determined that this issue behaves as intended based on the following:
The problem is the method type string passed to class_addMethod() by the test.
The test uses "v@". That's not a valid method type string because it does not have the selector's type. The test succeeds if you change it to use "v@:" (self=object, cmd=SEL, returns void) or better "@@:" (self=object, cmd=SEL, returns an object).