iOS面试

isKindOfClass 与 isMemberOfClass

2022-07-21  本文已影响0人  Bonew01

isKindOfClass 与 isMemberOfClass

// MJPerson类 继承 NSObject类

    // 这句代码的方法调用者不管是哪个类(只要是NSObject体系下的),都返回YES 基类的元类对象的superClass指针指向基类的类对象

        NSLog(@"%d", [NSObject isKindOfClass:[NSObject class]]); // 1 

        NSLog(@"%d", [NSObject isMemberOfClass:[NSObject class]]); // 0

        NSLog(@"%d", [MJPerson isKindOfClass:[MJPerson class]]); // 0  MJPerson的元类与MJPerson及MJPerson的子类不是同一个类

        NSLog(@"%d", [MJPerson isMemberOfClass:[MJPerson class]]); // 0  MJPerson的元类与MJPerson类不是同一个类

        NSLog(@"%d", [[MJPerson new] isKindOfClass:[MJPerson class]]); // 1    MJPerson实例对象所指向的类对象与MJPerson类对象 是同一个类

        NSLog(@"%d", [MJPerson isMemberOfClass:object_getClass([MJPerson class])]); // 1  MJPerson的元类与 MJPerson的元类相同

        object_getClass([MJPerson class])//获取MJPerson类对象的元类

  [A isKindOfClass:[B class]])  A 对象的类 与 B类或B的子类是否相同 (A的isa指针指向的类与B类或B的子类是否相同)

    [A isMemberOfClass:[B class]])  A 对象的类 与 B类是否相同 (A的isa指针指向的类与B类是否相同)

    NSLog(@"%d", [MJPerson isMemberOfClass:object_getClass([MJPerson class])]);//1

    object_getClass([MJPerson class]): 获取MJPerson类的元类

    类对象的isa指针指向元类对象

    基类的元类对象的superClass指针指向基类的类对象

///具体代码

    - (BOOL)isMemberOfClass:(Class)cls {

    return [self class] == cls;

}

- (BOOL)isKindOfClass:(Class)cls {

    for (Class tcls = [self class]; tcls; tcls = tcls->superclass) {

        if (tcls == cls) return YES;

    }

    return NO;

}

+ (BOOL)isMemberOfClass:(Class)cls {

    return object_getClass((id)self) == cls;

}

+ (BOOL)isKindOfClass:(Class)cls {

    for (Class tcls = object_getClass((id)self); tcls; tcls = tcls->superclass) {

        if (tcls == cls) return YES;

    }

    return NO;

}

上一篇下一篇

猜你喜欢

热点阅读