目录
一,实例方法
二,类方法
一,实例方法
1,实例代码
Person *person = [Person new];
NSLog(@"%d", [person isMemberOfClass:[Person class]]);
NSLog(@"%d", [person isMemberOfClass:[NSObject class]]);
NSLog(@"%d", [person isKindOfClass:[Person class]]);
NSLog(@"%d", [person isKindOfClass:[NSObject class]]);
// 打印
1
0
1
1
2,底层代码(源码下载地址)
- (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;
}
3,说明
-
isMemberOfClass
:该实例对象是否属于某个类 -
isKindOfClass
:该实例对象是否属于某个类或其子类
二,类方法
1,实例代码
NSLog(@"%d", [Person isMemberOfClass:[Person class]]);
NSLog(@"%d", [Person isMemberOfClass:[NSObject class]]);
NSLog(@"%d", [Person isKindOfClass:[Person class]]);
NSLog(@"%d", [Person isKindOfClass:[NSObject class]]);
// 打印
0
0
0
1
2,底层代码
// self是class对象,object_getClass(self)是meta-class对象
+ (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;
}
3,说明
-
isMemberOfClass
:该类是否等于某个类 -
isKindOfClass
:该类是否等于某个类或其子类
4,分析
- 方法内部是用
meta-class
对象进行判断的,而传进去的是class
对象,所以前三个都是0,必须传meta-class
对象才能得到正确的结果
NSLog(@"%d", [Person isMemberOfClass:object_getClass([Person class])]);
NSLog(@"%d", [Person isMemberOfClass:object_getClass([NSObject class])]);
NSLog(@"%d", [Person isKindOfClass:object_getClass([Person class])]);
// 打印
1
0
1
- 第四个虽然传的是
class
对象,但Person的meta-class
对象通过superclass
指针可以找到NSObject的class
对象,所以结果是1
网友评论