05 - 类 & isa 经典问题分析

元类 中为什么会有 类对象 的 类方法?

类的结构分析 中我们知道实例方法 存储在类中,类方法存储在元类中,下面我们通过面试题分析方法的归属问题

LGPerson中定义一个实例方法和一个类方法

@interface LGPerson : NSObject
- (void)sayHello;
+ (void)sayHappy;

@end

@implementation LGPerson

- (void)sayHello{
    NSLog(@"LGPerson say : Hello!!!");
}

+ (void)sayHappy{
    NSLog(@"LGPerson say : Happy!!!");
}

@end
void Objc_copyMethodList(Class pClass){
    unsigned int count = 0;
    Method *methods = class_copyMethodList(pClass, &count);
    for (unsigned int i=0; i < count; i++) {
        Method const method = methods[i];
        //获取方法名
        NSString *key = NSStringFromSelector(method_getName(method));
        
        LGLog(@"Method, name: %@", key);
    }
    free(methods);
}
void innstanceMethod_classToMetaclass(Class pClass){
    
    const char *className = class_getName(pClass);
    Class metaClass = objc_getMetaClass(className);
    
    Method method1 = class_getInstanceMethod(pClass, @selector(sayHello));
    Method method2 = class_getInstanceMethod(metaClass, @selector(sayHello));

    Method method3 = class_getInstanceMethod(pClass, @selector(sayHappy));
    Method method4 = class_getInstanceMethod(metaClass, @selector(sayHappy));
    
    LGLog(@"%s - %p-%p-%p-%p",__func__,method1,method2,method3,method4);
}

void classMethod_classToMetaclass(Class pClass){
    
    const char *className = class_getName(pClass);
    Class metaClass = objc_getMetaClass(className);
    
    Method method1 = class_getClassMethod(pClass, @selector(sayHello));
    Method method2 = class_getClassMethod(metaClass, @selector(sayHello));

    Method method3 = class_getClassMethod(pClass, @selector(sayHappy));
    // 元类 为什么有 sayHappy 类方法 0 1
    //
    Method method4 = class_getClassMethod(metaClass, @selector(sayHappy));
    
    LGLog(@"%s-%p-%p-%p-%p",__func__,method1,method2,method3,method4);
}
void IMP_classToMetaclass(Class pClass){
    
    const char *className = class_getName(pClass);
    Class metaClass = objc_getMetaClass(className);

    // - (void)sayHello;
    // + (void)sayHappy;
    IMP imp1 = class_getMethodImplementation(pClass, @selector(sayHello));
    IMP imp2 = class_getMethodImplementation(metaClass, @selector(sayHello));

    IMP imp3 = class_getMethodImplementation(pClass, @selector(sayHappy));
    IMP imp4 = class_getMethodImplementation(metaClass, @selector(sayHappy));

    NSLog(@"%s-%p-%p-%p-%p",__func__,imp1,imp2,imp3,imp4);
}
  • Objc_copyMethodList :用于获取类的方法列表
  • instanceMethod_classToMetaclass:获取类和元类的实例方法
  • classMethod_classToMetaclass;获取类和元类的类方法
  • IMP_classToMetaclass : 返回方法的具体实现

代码调用传入LGPerson 下面是打印结果

// 打印结果
Method, name: sayHello
lgInstanceMethod_classToMetaclass - 0x1000031b0-0x0-0x0-0x100003148
lgClassMethod_classToMetaclass-0x0-0x0-0x100003148-0x100003148
lgIMP_classToMetaclass-0x100001d10-0x7fff66861580-0x7fff66861580-0x100001d40

结果分析

Objc_copyMethodList函数
/** 
 * Describes the instance methods implemented by a class.
 * 
 * @param cls The class you want to inspect.
 * @param outCount On return, contains the length of the returned array. 
 *  If outCount is NULL, the length is not returned.
 * 
 * @return An array of pointers of type Method describing the instance methods 
 *  implemented by the class—any instance methods implemented by superclasses are not included. 
 *  The array contains *outCount pointers followed by a NULL terminator. You must free the array with free().
 * 
 *  If cls implements no instance methods, or cls is Nil, returns NULL and *outCount is 0.
 * 
 * @note To get the class methods of a class, use \c class_copyMethodList(object_getClass(cls), &count).
 * @note To get the implementations of methods that may be implemented by superclasses, 
 *  use \c class_getInstanceMethod or \c class_getClassMethod.
 */
OBJC_EXPORT Method _Nonnull * _Nullable
class_copyMethodList(Class _Nullable cls, unsigned int * _Nullable outCount) 
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

return描述信息里面已经说明:由类实现,不由父类实现的任何实例方法,所以LGPerson的方法列表打印结果只有sayHello方法

instanceMethod_classToMetaclass函数
/** 
 * Returns a specified instance method for a given class.
 * 
 * @param cls The class you want to inspect.
 * @param name The selector of the method you want to retrieve.
 * 
 * @return The method that corresponds to the implementation of the selector specified by 
 *  \e name for the class specified by \e cls, or \c NULL if the specified class or its 
 *  superclasses do not contain an instance method with the specified selector.
 *
 * @note This function searches superclasses for implementations, whereas \c class_copyMethodList does not.
 */
OBJC_EXPORT Method _Nullable
class_getInstanceMethod(Class _Nullable cls, SEL _Nonnull name)
    OBJC_AVAILABLE(10.0, 2.0, 9.0, 1.0, 2.0);

class_getInstanceMethod这个方法,主要是用于获取实例方法,并且如果在传入的类或者类的父类中没有找到指定的实例方法,则返回NULL

  • 0x1000031b0 -> LGPerson中存在 sayHello的实例方法
  • 0x0 元类中没有 sayHello的实例方法
  • 0x0 LGPerson中没有 sayHappy的实例方法
  • 0x100003148元类中有 sayHappy的实例方法
classMethod_classToMetaclass函数
/** 
 * Returns a pointer to the data structure describing a given class method for a given class.
 * 
 * @param cls A pointer to a class definition. Pass the class that contains the method you want to retrieve.
 * @param name A pointer of type \c SEL. Pass the selector of the method you want to retrieve.
 * 
 * @return A pointer to the \c Method data structure that corresponds to the implementation of the 
 *  selector specified by aSelector for the class specified by aClass, or NULL if the specified 
 *  class or its superclases do not contain an instance method with the specified selector.
 *
 * @note Note that this function searches superclasses for implementations, 
 *  whereas \c class_copyMethodList does not.
 */
OBJC_EXPORT Method _Nullable
class_getClassMethod(Class _Nullable cls, SEL _Nonnull name)
    OBJC_AVAILABLE(10.0, 2.0, 9.0, 1.0, 2.0);

return 描述信息里面已经说明:如果在传入的类或者类的父类中没有找到指定的类方法,则返回NULL

/***********************************************************************
* class_getClassMethod.  Return the class method for the specified
* class and selector.
**********************************************************************/
Method class_getClassMethod(Class cls, SEL sel)
{
    if (!cls  ||  !sel) return nil;

    return class_getInstanceMethod(cls->getMeta(), sel);
}

// NOT identical to this->ISA when this is a metaclass
Class getMeta() {
    if (isMetaClass()) return (Class)this;
    else return this->ISA();
}

上面代码可以看出class_getClassMethod其本质就是获取 元类实例方法 ,最终还是会走到 class_getInstanceMethod , 但是在这里需要注意的一点是:在 getMeta源码 中,如果判断出cls 是 元类,那么就不会再继续往下递归查找,会直接返回 this,其目的是为了防止元类的无限递归查找(根源类isa指向自己)

  • 0x0 pClass 是 LGPerson类 ,不是 元类 ,然后找 元类 --> 根元类 --> 根类 --> nil依次查找,最后返回 NULL
  • 0x0 pClass 是 LGPerson元类 , 然后找 元类 --> 根元类 --> 根类 --> nil依次查找,最后返回 NULL
  • 0x100003148 pClass 是 LGPerson类 ,不是 元类,然后找 元类 sayHappy实例方法,返回
  • 0x100003148 pClass 是 LGPerson元类 ,然后找 元类 sayHappy实例方法,返回

因为class_getClassMethod方法在元类的判断导致我们在元类中也能找到sayHappy类方法,这是苹果人为制造的 递归终止条件,目的就是防止无限次递归

lgIMP_classToMetaclass函数
IMP class_getMethodImplementation(Class cls, SEL sel)
{
    IMP imp;

    if (!cls  ||  !sel) return nil;

    //查找方法实现
    imp = lookUpImpOrNil(nil, sel, cls, LOOKUP_INITIALIZE | LOOKUP_RESOLVER);

    //如果没有找到,则进行消息转发
    if (!imp) {
        return _objc_msgForward;
    }

    return imp;
}

class_getMethodImplementation 主要是返回方法的具体实现,由源码可以看出返回的函数指针可能是一个指向runtime内部的函数,而不一定是方法的实际实现。如果类实例无法响应selector,则返回的函数指针将是运行时消息转发机制的一部分

  • 0x100001d10 根据LGPerson文件,可以得出LGPerson类中可以查找sayHello的具体实现,所以返回一个imp函数指针的地址
  • 0x7fff66861580根据类方法存储在元类中可知,sayHello是一个实例方法,并不存储在元类中,也没有其任何实现,所以进行了消息转发
  • 0x7fff66861580 sayHappy是一个类方法,并不存储在类中,也没有其任何实现,所以进行了消息转发
  • 0x100001d40 可以在元类中查找到sayHappy的具体实现,所以返回一个imp函数指针的地址

总结 :class_getMethodImplementation:获取方法的具体实现,如果未查找到,则进行消息转发

iskindOfClass &isMemberOfClass 的理解

//-----使用 iskindOfClass & isMemberOfClass 类方法
BOOL re1 = [(id)[NSObject class] isKindOfClass:[NSObject class]];       //
BOOL re2 = [(id)[NSObject class] isMemberOfClass:[NSObject class]];     //
BOOL re3 = [(id)[LGPerson class] isKindOfClass:[LGPerson class]];       //
BOOL re4 = [(id)[LGPerson class] isMemberOfClass:[LGPerson class]];     //
NSLog(@" re1 :%hhd\n re2 :%hhd\n re3 :%hhd\n re4 :%hhd\n",re1,re2,re3,re4);

//------iskindOfClass & isMemberOfClass 实例方法
BOOL re5 = [(id)[NSObject alloc] isKindOfClass:[NSObject class]];       //
BOOL re6 = [(id)[NSObject alloc] isMemberOfClass:[NSObject class]];     //
BOOL re7 = [(id)[LGPerson alloc] isKindOfClass:[LGPerson class]];       //
BOOL re8 = [(id)[LGPerson alloc] isMemberOfClass:[LGPerson class]];     //
NSLog(@" re5 :%hhd\n re6 :%hhd\n re7 :%hhd\n re8 :%hhd\n",re5,re6,re7,re8);

打印结果

2020-09-15 22:38:50.139130+0800 KCObjc[23825:541164]  
 re1 :1
 re2 :0
 re3 :0
 re4 :0
2020-09-15 22:38:50.139506+0800 KCObjc[23825:541164]  
 re5 :1
 re6 :1
 re7 :1
 re8 :1

让我们先看下源码在进行结果分析
-isKindOfClass 源码解析(实例方法 & 类方法)

//--isKindOfClass---类方法、对象方法
//+ isKindOfClass:第一次比较是 获取类的元类 与 传入类对比,再次之后的对比是获取上次结果的父类 与 传入 类进行对比
+ (BOOL)isKindOfClass:(Class)cls {
    // 获取类的元类 vs 传入类
    // 根元类 vs 传入类
    // 根类 vs 传入类
    // 举例:LGPerson vs 元类 (根元类) (NSObject)
    for (Class tcls = self->ISA(); tcls; tcls = tcls->superclass) {
        if (tcls == cls) return YES;
    }
    return NO;
}

//- isKindOfClass:第一次是获取对象类 与 传入类对比,如果不相等,后续对比是继续获取上次 类的父类 与传入类进行对比
- (BOOL)isKindOfClass:(Class)cls {
/*
获取对象的类 vs 传入的类 
父类 vs 传入的类
根类 vs 传入的类
nil vs 传入的类
*/
    for (Class tcls = [self class]; tcls; tcls = tcls->superclass) {
        if (tcls == cls) return YES;
    }
    return NO;
}

  • isMemberOfClass 源码解析(实例方法 & 类方法)
//-----类方法
//+ isMemberOfClass : 获取类的元类,与 传入类对比
+ (BOOL)isMemberOfClass:(Class)cls {
    return self->ISA() == cls;
}
//-----实例方法
//- isMemberOfClass : 获取对象的类,与 传入类对比
- (BOOL)isMemberOfClass:(Class)cls {
    return [self class] == cls;
}

分析 :

  • re1 1 NSObject -> isa 即 NSObject 的元类 与 NSObject 不相等, 继续循环 ,NSObject 的元类的父类为NSObject ,相等 返回1
  • re2 0 NSObject -> isa 即 NSObject 的元类 与 NSObject 不相等 返回0
  • re3 0 LGPerson -> isaLGPerson 的元类 != LGPerson
    ,继续循环 LGPerson 的元类的父类 根元类 != LGPerson
    继续 根元类 的父类 NSObject != LGPerson
    NSObject 的父类nil != LGPerson 结束循环 返回0
  • re4 0 LGPerson -> isa 即 LGPerson 的元类 与 LGPerson 不相等 返回0

实例方法

  • re5 1 获取对象的类NSObject vs 传入的类NSObject 相等
  • re6 1 获取对象的类 NSObject vs 传入的类NSObject 相等
  • re7 1 获取对象的类 LGPerson vs 传入的类LGPerson 相等
  • re8 1 获取对象的类 LGPerson vs 传入的类LGPerson 相等
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容