1. 类对象获取
LSPerson *person = [[LSPerson alloc] init];
NSLog(@"[person class] = %@, isMetaClass=%d", [person class], class_isMetaClass([person class]));
NSLog(@"[LSPerson class] = %@, isMetaClass=%d", [LSPerson class], class_isMetaClass([LSPerson class]));
output:
//[person class] = LSPerson, isMetaClass=0
//[LSPerson class] = LSPerson, isMetaClass=0
根据以上代码可以看到不管是对象调用class
方法还是类调用class
方法,得到的都是类对象,且不是元类对象,那么class
底层是如何实现的呢?
class
源码
+ (Class)class {
return self;
}
- (Class)class {
return object_getClass(self);
}
可以看到class
的类方法直接返回调用类的类对象;实例方法调用object_getClass
且参数为实例对象。
object_getClass
源码
Class object_getClass(id obj)
{
if (obj) return obj->getIsa();
else return Nil;
}
获取当前对象的isa并返回,之前已经分析过对象的isa指向当前的类对象。
总结:不管是对象调用
class
方法还是类调用class
方法,返回的都是类对象。
2. 获取元类对象
那么如何获取元类对象呢?在runtime中有objc_getMetaClass(const char * _Nonnull name)
,参数是类名称的c语言字符串
const char *className = [NSStringFromClass([LSPerson class]) UTF8String];
Class metaClass = objc_getMetaClass(className);
NSLog(@"LSPerson metaClass = %@, isMetaClass=%d", metaClass, class_isMetaClass(metaClass));
output:
//LSPerson metaClass = LSPerson, isMetaClass=1
objc_getMetaClass
源码
Class objc_getMetaClass(const char *aClassName)
{
Class cls;
if (!aClassName) return Nil;
//根据类对象名称字符串获取类对象
cls = objc_getClass (aClassName);
if (!cls)
{
_objc_inform ("class `%s' not linked into application", aClassName);
return Nil;
}
//返回类对象的isa指针指向 即元类对象
return cls->ISA();
}
objc_getClass
源码 根据字符串获取类
Class objc_getClass(const char *aClassName)
{
if (!aClassName) return Nil;
// NO unconnected, YES class handler
return look_up_class(aClassName, NO, YES);
}
3. isKindOfClass和isMemberOfClass
isKindOfClass
的对象方法 和 类方法
- (BOOL)isKindOfClass:(Class)cls {
for (Class tcls = [self class]; tcls; tcls = tcls->superclass) {
if (tcls == cls) return YES;
}
return NO;
}
+ (BOOL)isKindOfClass:(Class)cls {
for (Class tcls = self->ISA(); tcls; tcls = tcls->superclass) {
if (tcls == cls) return YES;
}
return NO;
}
分析:
- (BOOL)isKindOfClass:(Class)cls
对象方法,首先获取对象的类对象tcls
和要比较的对象cls
进行比较,如果不想等则递归比较tcls
的父类。
+ (BOOL)isKindOfClass:(Class)cls
类方法,首先获取类的isa指针的指向,即元类tcls
与要比较的cls
进行比较,如果不想等,则递归查找tcls
的父类进行比较
isMemberOfClass
的对象方法 和 类方法
- (BOOL)isMemberOfClass:(Class)cls {
return [self class] == cls;
}
+ (BOOL)isMemberOfClass:(Class)cls {
return self->ISA() == cls;
}
分析:
- (BOOL)isMemberOfClass:(Class)cls
对象方法,比较对象的类对象和cls
是否想等。
+ (BOOL)isMemberOfClass:(Class)cls
类方法,获取类对象的元类和cls
比较是否想等。
题目解析:
//---类方法调用
BOOL re1 = [(id)[NSObject class] isKindOfClass:[NSObject class]];
//获取[NSObject class]的元类和[NSObject class]进行比较,不相等,则
//查找[NSObject class]的元类的父类,根元类的父类指向根类,都为
//[NSObject class]所以相等,结果为1
BOOL re2 = [(id)[NSObject class] isMemberOfClass:[NSObject class]];
//获取[NSObject class]的元类和[NSObject class]比较,不相等,结果为0
BOOL re3 = [(id)[LSPerson class] isKindOfClass:[LSPerson class]];
//获取[LSPerson class]的元类和[LSPerson class]进行比较,不相等
//则查找[LSPerson class]的元类的父类为根元类,和[LSPerson class]进行比较,不相等
//根元类的父类指向根类,和[LSPerson class]进行比较,不相等
//根类的父类指向nil,结果为0
BOOL re4 = [(id)[LSPerson class] isMemberOfClass:[LSPerson class]];
//获取[LSPerson class]的元类和[LSPerson class]比较,不相等,结果为0
//---实例方法调用
BOOL re5 = [(id)[NSObject alloc] isKindOfClass:[NSObject class]];
//获取[NSObject alloc]的类对象[[NSObject alloc] class] 和 [NSObject class]比较相等,结果为1
BOOL re6 = [(id)[NSObject alloc] isMemberOfClass:[NSObject class]];
//比较[NSObject alloc]的类对象[[NSObject alloc] class] 和 [NSObject class]相等,结果为1
BOOL re7 = [(id)[LSPerson alloc] isKindOfClass:[LSPerson class]];
//比较[LSPerson alloc]的类对象[[LSPerson alloc] class] 和 [LSPerson class]相等,结果为1
BOOL re8 = [(id)[LSPerson alloc] isMemberOfClass:[LSPerson class]];
//比较[LSPerson alloc]的类对象[[LSPerson alloc] class] 和 [LSPerson class]相等,结果为1
注意:
不管是根据断点源码还是根据查看汇编,在调用isKindOfClass
时并没有走到NSObject.mm
中的isKindOfClass
对象方法和类方法,反而走的是objc_opt_isKindOfClass
,这是因为llvm对一些不经常重写的方法进行了优化,如果重写了,则进行msgSend消息发送流程。
llvm中对部分方法进行转发
// This is the table of ObjC "accelerated dispatch" functions. They are a set
// of objc methods that are "seldom overridden" and so the compiler replaces the
// objc_msgSend with a call to one of the dispatch functions. That will check
// whether the method has been overridden, and directly call the Foundation
// implementation if not.
// This table is supposed to be complete. If ones get added in the future, we
// will have to add them to the table.
const char *AppleObjCTrampolineHandler::g_opt_dispatch_names[] = {
"objc_alloc",
"objc_autorelease",
"objc_release",
"objc_retain",
"objc_alloc_init",
"objc_allocWithZone",
"objc_opt_class",
"objc_opt_isKindOfClass",
"objc_opt_new",
"objc_opt_respondsToSelector",
"objc_opt_self",
};
objc_opt_isKindOfClass
源码
// Calls [obj isKindOfClass]
BOOL
objc_opt_isKindOfClass(id obj, Class otherClass)
{
#if __OBJC2__
printf("objc_opt_isKindOfClass(id obj, Class otherClass)");
if (slowpath(!obj)) return NO;
Class cls = obj->getIsa();
if (fastpath(!cls->hasCustomCore())) {
for (Class tcls = cls; tcls; tcls = tcls->superclass) {
if (tcls == otherClass) return YES;
}
return NO;
}
#endif
return ((BOOL(*)(id, SEL, Class))objc_msgSend)(obj, @selector(isKindOfClass:), otherClass);
}
分析:如果是objc2,则根据传入对象的isa获取到Class cls
,此处如果传入实例对象则获取类对象,如果传入类对象,则获取元类,然后递归cls
及其父类,和otherClass
进行比较。
4. class_getClassMethod
底层实现
Method class_getClassMethod(Class cls, SEL sel)
{
if (!cls || !sel) return nil;
return class_getInstanceMethod(cls->getMeta(), sel);
}
Class getMeta() {
if (isMetaClass()) return (Class)this;
else return this->ISA();
}
可以看到,获取类方法其实是根据类找到元类,然后去元类中找实例方法,从而侧面证明了,在OC中区分的对象方法和类方法,其实在C和C++层面并没有区分,都是方法,只是存储的位置不一样。
class_getInstanceMethod
源码
Method class_getInstanceMethod(Class cls, SEL sel)
{
if (!cls || !sel) return nil;
// This deliberately avoids +initialize because it historically did so.
// This implementation is a bit weird because it's the only place that
// wants a Method instead of an IMP.
#warning fixme build and search caches
// Search method lists, try method resolver, etc.
lookUpImpOrForward(nil, sel, cls, LOOKUP_RESOLVER);
#warning fixme build and search caches
return _class_getMethod(cls, sel);
}
static Method _class_getMethod(Class cls, SEL sel)
{
mutex_locker_t lock(runtimeLock);
return getMethod_nolock(cls, sel);
}
static method_t *
getMethod_nolock(Class cls, SEL sel)
{
method_t *m = nil;
runtimeLock.assertLocked();
// fixme nil cls?
// fixme nil sel?
ASSERT(cls->isRealized());
while (cls && ((m = getMethodNoSuper_nolock(cls, sel))) == nil) {
cls = cls->superclass;
}
return m;
}
image.png注意:while循环是从cls开始,递归其父类进行查找,所以如果在元类中查找类方法,直到根元类仍没有找到,则因为根元类的父类为根类即
NSObject
,如果在NSObject
中实现了同名的对象方法,仍然不会报错。
如上图所示,如果调用[LSStudent sleep];
,并不会报unrecognized selector sent to class
的错误,反而会调用根类中的- (void)sleep
实例方法。
网友评论