一、举例说明:
NSLog(@"%d",[[NSObject class] isKindOfClass:[NSObject class]]); 结果:1
NSLog(@"%d",[[NSObject class] isMemberOfClass:[NSObject class]]);结果:0
NSLog(@"%d",[[lzhPerson class] isKindOfClass:[lzhPerson class]]);结果:0
NSLog(@"%d",[[lzhPerson class] isMemberOfClass:[lzhPerson class]]);结果:0
NSLog(@"---%d",[lzhPerson isKindOfClass:[NSObject class]]);结果:1
二:分析底层实现如下:
+ (BOOL)isMemberOfClass:(Class)cls {
return object_getClass((id)self) == cls;
从上面等式可以看出来:是直接判断元类对象是否相等
}
- (BOOL)isMemberOfClass:(Class)cls {
return [self class] == cls;
从上面等式看出来:当前类型是否是传进来的参数比较2个是否相等
}
+ (BOOL)isKindOfClass:(Class)cls {
判断元类对象是否相等于传入的元类的以及传入的元类的子类
for(Class tcls = object_getClass((id)self); tcls; tcls = tcls->superclass) {
if(tcls == cls)returnYES;
}
return NO;
}
- (BOOL)isKindOfClass:(Class)cls {
判断传入的参数是否等于当前类,如果不等于就遍历当前类的父类是否等于传入的参数;如果不等于继续查找当前类的父类
for(Class tcls = [selfclass]; tcls; tcls = tcls->superclass) {
if(tcls == cls)returnYES;
}
return NO;
}
网友评论