A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© holmesconan 中级黑马   /  2015-12-26 00:11  /  534 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

不久重构一个类, 用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)


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马