5

我试图更好地理解 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

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

4

1 回答 1

3

在这种情况下发生的事情是您假设attributedString是 type NSAttributedString,但事实并非如此:

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

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

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

于 2013-04-19T17:53:42.663 回答