原始链接
原文链接
官方文档
官方文档
Demo-Github
isKindOfClass
Returns a Boolean value that indicates whether the receiver is an instance of given class or an instance of any class that inherits from that class.
返回一个布尔值,该值指示接收方是给定类的实例还是从该类继承的任何类的实例。
- 对象方法
- 参数为Class
- 改对象是否是该类的,或者该类父类的一个实例对象
-
isMemberOfClass
Returns a Boolean value that indicates whether the receiver is an instance of a given class.
返回一个布尔值,该值指示接收方是否是给定类的实例 - 对象方法
- 参数为Class
- 改对象是否是该类的一个实例对象
BOOL res1 = [(id)[NSObject class] isKindOfClass:[NSObject class]];
BOOL res2 = [(id)[NSObject class] isMemberOfClass:[NSObject class]];
BOOL res3 = [(id)[Person class] isKindOfClass:[Person class]];
BOOL res4 = [(id)[Person class] isMemberOfClass:[Person class]];
+ (Class)class OBJC_SWIFT_UNAVAILABLE("use 'aClass.self' instead");
+ (Class)class {
return self;
}
+ (BOOL)isKindOfClass:(Class)cls {
for (Class tcls = object_getClass((id)self); tcls; tcls = tcls->superclass) {
if (tcls == cls) return YES;
}
return NO;
}
Class object_getClass(id obj)
{
if (obj) return obj->getIsa();
else return Nil;
}
+ (BOOL)isMemberOfClass:(Class)cls {
return object_getClass((id)self) == cls;
}
- [NSObject class] 返回值是?
- 返回NSObject这个类,有一个坑在这里就是NSObject的metaclass 是指向自己的,
- 因为这是最顶层。
- 所以 res1 YES, NSObject 是自己父类的子类的isa
- [NSObject class] 返回值是?
- NSObject 是自己父类的instance, 但是不是当前类的instance
- 3 和 4 同理
res1:1
res2:0
res3:0
res4:0
续集
BOOL res5 = [(id)[Person new] isMemberOfClass:[Person class]];
BOOL res6 = [(id)[Person new] isKindOfClass:[Person class]];
BOOL res7 = [(id)[Teacher new] isMemberOfClass:[Person class]];
BOOL res8 = [(id)[Teacher new] isKindOfClass:[Person class]];
res5:1
res6:1
res7:0
res8:1
网友评论