gpt4 book ai didi

objective-c - 为什么在调用类别实例方法后仍无法获取它?

转载 作者:太空狗 更新时间:2023-10-30 03:53:18 24 4
gpt4 key购买 nike

我正在努力更好地理解 Objective-C 运行时。考虑 NSAttributedString.h,它有一个最小的接口(interface),后面是一个更广泛的类别 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

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

最佳答案

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

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

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

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

关于objective-c - 为什么在调用类别实例方法后仍无法获取它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16110283/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com