Why can't I get the method of the category instance even after calling it?

I am trying to understand the Objective-C runtime a little better. Consider NSAttributedString.hwhich has a minimal interface, followed by a more extensive category NSExtendedAttributedString.

Now consider the following code:

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

We find an instance method that is part of the canonical interface, but not one that belongs to the category. How can this happen, and yet it can be successfully called? Is there a way to research and find a category method?

+5
source share
1 answer

What happens in this case, you assume it attributedStringhas a type NSAttributedString, which is not so:

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

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

NSAttributedString.class [attributedString class], .

+3

All Articles