isKindOfClass:和isMemberOfClass的用

2018-09-29  本文已影响0人  Gxdy

本文将从NSObject源码的角度来讲述isKindOfClassisKindOfClass使用.
如需要查看更多更新源码资源请前往苹果官方源码下载

在进入正文之前先附上一张isa与superclass指针的指向结构图

isa与superclass.png
  1. - isKindOfClass:(实例方法)
- (BOOL)isKindOfClass:(Class)cls {
    // 循环遍历直到匹配到对应class或者tcls==nil
    // (从上图可以知道tcls->superclass最终会指向nil)
    for (Class tcls = [self class]; tcls; tcls = tcls->superclass) {
        if (tcls == cls) return YES;
    }
    return NO;
}
UIView *view = [[UIView alloc] init];
[view isKindOfClass: [UIView class]];     // --> YSE
[view isKindOfClass: [NSObject class]];   // --> YSE
  1. + isKindOfClass:(类对象方法)
+ (BOOL)isKindOfClass:(Class)cls {
    for (Class tcls = object_getClass((id)self); tcls; tcls = tcls->superclass) {
        if (tcls == cls) return YES;
    }
    return NO;
}
[UILabel isKindOfClass: [UILabel class]];     // --> NO,元类对象 != [UILabel class](类对象)
[UILabel isKindOfClass: object_getClass([UILabel  class])];   // --> YSE
[[UILabel  class] isKindOfClass: object_getClass([UILabel  class])];  // --> YSE
[[UILabel  class] isKindOfClass: object_getClass([UIView  class])];  // --> YSE
[[UILabel  class] isKindOfClass: object_getClass([NSObject  class])];  // --> YSE
[[UILabel  class] isKindOfClass: [NSObject  class]];  // --> YSE
  1. - isMemberOfClass:(实例方法)
- (BOOL)isMemberOfClass:(Class)cls {
    return [self class] == cls;
}
[[UILabel new] isMemberOfClass:[UILabel class]]; // YES
 [[UILabel new] isMemberOfClass:[UIView class]]; // NO
  1. + isMemberOfClass:(类对象方法)
+ (BOOL)isMemberOfClass:(Class)cls {
    return object_getClass((id)self) == cls;
}
[UILabel isMemberOfClass:[UIView class]];  // NO
[UILabel isMemberOfClass:object_getClass([UILabel  class])];  // YES
  1. 总结
  1. 不管是isKindOfClass还是isMemberOfClass
  1. isKindOfClass具有继承关系,会沿着superclass遍历;isMemberOfClass,则没有继承关系,只会判断一次

3.注意点与用法:

上一篇下一篇

猜你喜欢

热点阅读