isa与class经典问题

2020-09-16  本文已影响0人  miaohy
 BOOL re1 = [(id)[NSObject class] isKindOfClass:[NSObject class]];  
//返回yes
+ (BOOL)isKindOfClass:(Class)cls {
    for (Class tcls = self->ISA(); tcls; tcls = tcls->superclass) {
        if (tcls == cls) return YES;
    }
    return NO;
}

+ (Class)class {
    return self;
}

上面为什么返回YES呢?[NSObject class] 返回类对象NSObject,NSObject调用isKindOfClass方法,首先是取到NSObject的元类与NSObject比较,不相等,然后取到NSObject元类的父类(NSObject元类的父类是NSObject)进行比较,相等。

BOOL re2 = [(id)[NSObject class] isMemberOfClass:[NSObject class]];  

+ (BOOL)isMemberOfClass:(Class)cls {
   return self->ISA() == cls;
}

上面返回NO,为啥呢?NSObject调用isMemberOfClass方法,取的NSObject的元类与NSObject比较不相等

BOOL re3 = [(id)[LGPerson class] isKindOfClass:[LGPerson class]];       //

上面返回NO,为啥呢?[LGPerson class] LGPerson类对象,调用isKindOfClass ,首先取LGPerson的元类与LGPerson比较发现不相等,然后再取LGPerson元类的父类(NSObject的元类)与LGPerson比较,也不相等,再取NSObject的元类的父类(NSObject)与LGPerson比较还不相等,再再然后取NSObject的父类位nil与LGPerson比较,也不相等,因为为nil所以跳出循环,最后返回NO

BOOL re4 = [(id)[LGPerson class] isMemberOfClass:[LGPerson class]];     //

上面返回NO,为啥呢?[LGPerson class] 返回LGPerson类对象,再调用isMemberOfClass,会拿LGPerson类对象的isa即元类与LGPerson类对象比较,所以不相等

 BOOL re5 = [(id)[NSObject alloc] isKindOfClass:[NSObject class]];   
- (BOOL)isKindOfClass:(Class)cls {
    for (Class tcls = [self class]; tcls; tcls = tcls->superclass) {
        if (tcls == cls) return YES;
    }
    return NO;
}
- (Class)class {
    return object_getClass(self);
}

Class object_getClass(id obj)
{
    if (obj) return obj->getIsa();
    else return Nil;
} 

上面为什么返回YES呢?[NSObject alloc]一个NSObject的实例对象,调用isKindOfClass,该方法首先通过 [self class]拿到NSObject的类对象,然后与传过来的类对象进行比较,两者相等

BOOL re6 = [(id)[NSObject alloc] isMemberOfClass:[NSObject class]];
- (BOOL)isMemberOfClass:(Class)cls {
    return [self class] == cls;
}

NSObject的实例对象调用isMemberOfClass,该函数是拿实例对象的class即类对象与[NSObject class]比较,所以相等

BOOL re7 = [(id)[LGPerson alloc] isKindOfClass:[LGPerson class]]; 
BOOL re8 = [(id)[LGPerson alloc] isMemberOfClass:[LGPerson class]];  ```
//LGPerson的实例对象调用isMemberOfClass,该函数是拿实例对象的class即类对象与[LGPerson class]比较,所以相等
上一篇下一篇

猜你喜欢

热点阅读