黑马程序员技术交流社区

标题: @protocol 的一个小细节 [打印本页]

作者: holmesconan    时间: 2015-12-26 00:11
标题: @protocol 的一个小细节
不久重构一个类, 用protocol做了一些特别的事情, 结果被坑了. 先不说怎么被坑, 我们来一段代码, 大伙猜猜结果是啥?


       
@protocol ProtocolA  @end
@protocol ProtocolB  @end
@interface ClassB : NSObject  @end
@protocol ProtocolC  @end
@interface ClassC : NSObject  @end
@implementation ClassC @end
{
    Protocol *a = NSProtocolFromString(@"ProtocolA");
    NSLog(@"%@", a);
    Protocol *b = NSProtocolFromString(@"ProtocolB");
    NSLog(@"%@", b);
    Protocol *c = NSProtocolFromString(@"ProtocolC");
    NSLog(@"%@", c);
}

结果是

       
2015-12-09 17:37:54.303 ProtocolTest[990:47869] (null)
2015-12-09 17:37:54.303 ProtocolTest[990:47869] (null)
2015-12-09 17:37:54.304 ProtocolTest[990:47869]

ProtocolA, ProtocolB竟然是null. 为什么会取不到值呢?

我猜测是protocol初始化的问题. 先去看看protocol的定义:

       
#elif __OBJC2__
#include // All methods of class Protocol are unavailable.
// Use the functions in objc/runtime.h instead.
__OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0)
@interface Protocol : NSObject
@end
#else
!__OBJC2__ 直接略过
#endif

可见Protocol也是一个类.

这时我猜测

       
@protocol ProtocolC  @end

只是申明了一个类, 实际编译后并没有这个类.

我们来写一段测试代码, 写一个只有声明的类, 看看最终有没有这个类,

       
@interface ClassD : NSObject @end
    Class dd = NSClassFromString(@"ClassD");
    NSLog(@"%@", dd);

果然输出的结果是null

       
2015-12-09 20:42:36.315 ProtocolTest[735:11451] (null)







欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2