为什么即使在调用之后我也无法获得类别实例方法?

Ben*_*ynn 5 objective-c nsattributedstring objective-c-category

我试图更好地理解Objective-C运行时.考虑NSAttributedString.h哪个具有最小接口,后跟更广泛的类别NSExtendedAttributedString.

现在考虑以下代码:

NSAttributedString *attributedString = [[NSAttributedString alloc] initWithAttributedString:[[NSAttributedString alloc] initWithString:@"ABC"]];
NSLog(@"Result: %@", attributedString); 
NSLog(@"Exists? %@", [NSString stringWithUTF8String:sel_getName(method_getName(class_getInstanceMethod(NSAttributedString.class, @selector(initWithAttributedString:))))]);    
NSLog(@"Exists? %@", [NSString stringWithUTF8String:sel_getName(method_getName(class_getInstanceMethod(NSAttributedString.class, @selector(string))))]);

// Produces this output
2013-04-19 10:17:35.364 TestApp[53300:c07] Result: ABC{
}
2013-04-19 10:17:35.364 TestApp[53300:c07] Exists? <null selector>
2013-04-19 10:17:35.365 TestApp[53300:c07] Exists? string
Run Code Online (Sandbox Code Playgroud)

我们发现实例方法是规范接口的一部分,但不是类别中的实例方法.这怎么可能发生,但它可以被成功调用?有没有办法反省并找到类别方法?

pro*_*oxi 3

在这种情况下,您假设attributedString类型为NSAttributedString,但事实并非如此:

NSLog(@"Class: %@", [attributedString class]);

// Produces this output
2013-04-19 19:50:21.955 TestApp[1611:303] Class: NSConcreteAttributedString
Run Code Online (Sandbox Code Playgroud)

如果您更改NSAttributedString.class代码,[attributedString class]它将按预期工作。