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

时间:2013-04-19 17:26:08

标签: 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

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

1 个答案:

答案 0 :(得分:3)

在这种情况下,您认为attributedString属于NSAttributedString类型,情况并非如此:

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

// Produces this output
2013-04-19 19:50:21.955 TestApp[1611:303] Class: NSConcreteAttributedString

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