
作者:曉月 授權本站轉載。
前不久重構一個類, 用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)