isKindOfClass和isMemberOfClass的區別

lmg4819發表於2018-05-03

isKindOfClass的實現程式碼如下:

-(BOOL)isKindOfClass:(Class)aClass

{

            for (Class tcls = isa; tcls; tcls-> superclass) {

                     if (tcls == aClass) {

                             return YES;

                     }

            }

        return NO;

}

isMemberOfClass的實現程式碼如下:

-(BOOL)isMemberOfClass:(Class)aClass

{

          return isa == aClass;

}

如果呼叫這兩個方法的是物件,isa指標指向的是物件的Class,如果呼叫這兩個方法的是Class,isa指標指向的是類的元類,接下來通過一張圖介紹一下物件,類,元類之間的關係:

isKindOfClass和isMemberOfClass的區別

如圖:Father為繼承自NSObject的類,Son為繼承自Father的類,接下來,我們們通過幾個例項來驗證上述方法的正確性:

  Son *sonObject = [Son new];

Father *fatherObject = [Father new];

BOOL ret1 = [Son isKindOfClass:[fatherObject class]];//0

BOOL ret2 = [sonObject isKindOfClass:[Father class]];//1

BOOL ret3 = [Son isMemberOfClass:[fatherObject class]];//0

BOOL ret4 = [sonObject isMemberOfClass:[Father class]];//0

NSLog(@"%d------%d-------%d-------%d",ret1,ret2,ret3,ret4);

列印結果:

isKindOfClass和isMemberOfClass的區別

分析這四個問題答案的過程如下:

 /*

Son->(isa)MetaClassOfSon->(superClass)MetaClassOfFather->(superClass)MetaClassOfNSObjetc->(superClass)NSObject->(superClass)nil

[father class] = Father

*/

BOOL ret1 = [Son isKindOfClass:[fatherObject class]];//0

/*

sonObject->(isa)Son->(superClass)Father->(superClass)NSObject->(superClass)nil

[Father class] = Father

*/

BOOL ret2 = [sonObject isKindOfClass:[Father class]];//1

 /*

Son->(isa)MetaClassOfSon

[fatherObject class] = Father

*/

BOOL ret3 = [Son isMemberOfClass:[fatherObject class]];//0

/*

sonObject->(isa)Son

[Father class] = Father

*/

BOOL ret4 = [sonObject isMemberOfClass:[Father class]];//0




相關文章