天天看点

@protocol的一个小细节@protocol的一个小细节

@protocol的一个小细节

前不久重构一个类, 用protocol做了一些特别的事情, 结果被坑了. 先不说怎么被坑, 我们来一段代码, 大伙猜猜结果是啥?

@protocol ProtocolA <NSObject> @end


@protocol ProtocolB <NSObject> @end
@interface ClassB : NSObject <ProtocolB> @end


@protocol ProtocolC <NSObject> @end
@interface ClassC : NSObject <ProtocolC> @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] <Protocol: 0x1012a02c0>
           

ProtocolA

,

ProtocolB

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

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

#elif __OBJC2__

#include <objc/NSObject.h>

// 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

也是一个类.

这时我猜测

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

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

@interface ClassD : NSObject @end

    Class dd = NSClassFromString(@"ClassD");
    NSLog(@"%@", dd);
           

果然输出的结果是null

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