class和superclass源码(runtime源码里有)
Foundation框架里NSObject框架里的有些基础方法是开源的,
objc4源码链接 https://opensource.apple.com/tarballs/objc4/
在源码里搜索NSOject.mm文件,然后搜索class就找到源码了
class的作用是获取对象的类对象,superclass的作用是获取父类。
源码
+ (Class)class {
return self;
}
- (Class)class {
return object_getClass(self);
}
+ (Class)superclass {
return self->superclass;
}
- (Class)superclass {
return [self class]->superclass;
}
isMemberOfClass
左边对象的类对象是否等于右边的类对象
isKindOfClass
左边的类对象是否是等于右边类对象,或者是右边类对象的子类
源码
重点
看调用方法的是实例对象还是类对象,或者说看是类方法还是对象方法,类方法调用的话,object_getClass((id)self),这行代码得到的是元类对象,那右边传入的类也应该是元类对象才会相等。右边传入的如果是NSObject,只要左边是NSObject的子类,一般是成立的。
+ (BOOL)isMemberOfClass:(Class)c ls {
return object_getClass((id)self) == cls;
}
- (BOOL)isMemberOfClass:(Class)cls {
return [self class] == cls;
}
+ (BOOL)isKindOfClass:(Class)cls {
for (Class tcls = object_getClass((id)self); tcls; tcls = tcls->superclass) {
if (tcls == cls) return YES;
}
return NO;
}
- (BOOL)isKindOfClass:(Class)cls {
for (Class tcls = [self class]; tcls; tcls = tcls->superclass) {
if (tcls == cls) return YES;
}
return NO;
}
+ (BOOL)isSubclassOfClass:(Class)cls {
for (Class tcls = self; tcls; tcls = tcls->superclass) {
if (tcls == cls) return YES;
}
return NO;
}