加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

objective-c – 为什么即使在调用它之后我也无法获得我的类别实

发布时间:2020-12-16 05:04:20 所属栏目:百科 来源:网络整理
导读:我试图更好地理解Objective-C运行时.考虑NSAttributedString.h,它具有最小的接口,后跟更广泛的类别NSExtendedAttributedString. 现在考虑以下代码: NSAttributedString *attributedString = [[NSAttributedString alloc] initWithAttributedString:[[NSAttr
我试图更好地理解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? %@",@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

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

解决方法

在这种情况下发生的是你假设attributionString属于NSAttributedString类型,但情况并非如此:
NSLog(@"Class: %@",[attributedString class]);

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读