
作者:曉月,授權本站轉載。
日前重構一個類別時用 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);
實際輸出:
ProtocolTest[990:47869] (null) ProtocolTest[990:47869] (null) ProtocolTest[990:47869] ProtocolC
ProtocolA 與 ProtocolB 竟然是 nil。為什麼拿不到?
初步猜測與 protocol 的「初始化」有關,於是回頭看 Protocol 的定義:
#elif __OBJC2__ #include <objc/runtime.h> // All methods of class Protocol are unavailable. // Use the functions in objc/runtime.h instead @interface Protocol : NSObject @end
也就是說,Protocol 本身就是一個類別。接著的推論是:@protocol ProtocolC @end 只是宣告,編譯後並不存在名為 ProtocolC 的類別。
寫段程式驗證——宣告一個只有介面、沒有實作的類別,再試著取回它:
@interface ClassD : NSObject @end Class *dd = NSClassFromString(@"ClassD"); NSLog(@"%@", dd);
輸出果然也是:
ProtocolTest[735:11451] (null)
結論很清楚:只有宣告而沒有任何實作的類別,在執行期並不存在。回頭看第一段程式碼,ProtocolC 之所以有值,是因為它後面跟著 ClassC 的實作,編譯器為此生成了對應符號;ProtocolA、ProtocolB 則從頭到尾沒人實作,自然查表不到。這個細節在動態查詢型別時很容易踩到,值得記住。