iOS isKindOfClass與isMemberOfClass的區別

GabrielPanda發表於2019-01-18

先看一下官方文件的說法

isKindOfClass: Returns a Boolean value that indicates whether the receiver is
 an instance of given class or an instance of any class that inherits from that class.
//呼叫者是給定類的例項或者是給定類的子類的例項

isMemberOfClass: Returns a Boolean value that indicates 
whether the receiver is an instance of a given class.
//呼叫者是否是給定類的例項
複製程式碼

然後看一道題目:

BOOL res1 = [(id)[NSObject class] isKindOfClass:[NSObject class]];
BOOL res2 = [(id)[NSObject class] isMemberOfClass:[NSObject class]];
BOOL res3 = [(id)[xxObj class] isKindOfClass:[xxObj class]];
BOOL res4 = [(id)[xxObj class] isMemberOfClass:[xxObj class]];

複製程式碼

答案是:YES / NO / NO / NO

協議有一套類方法的隱藏實現,所以編譯執行正常; 由於NSObject meta class的父類為NSObject class,所以只有第一句為YES 看一下圖就明白了:

class-meta class

相關文章