元類 中為什么會有 類對象 的 類方法问潭?
在 類的結(jié)構分析 中我們知道實例方法 存儲在類中熄赡,類方法存儲在元類中,下面我們通過面試題分析方法的歸屬問題
在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
: 返回方法的具體實現(xiàn)
代碼調(diào)用傳入LGPerson
下面是打印結(jié)果
// 打印結(jié)果
Method, name: sayHello
lgInstanceMethod_classToMetaclass - 0x1000031b0-0x0-0x0-0x100003148
lgClassMethod_classToMetaclass-0x0-0x0-0x100003148-0x100003148
lgIMP_classToMetaclass-0x100001d10-0x7fff66861580-0x7fff66861580-0x100001d40
結(jié)果分析
Objc_copyMethodList
函數(shù)
/**
* 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
描述信息里面已經(jīng)說明:由類實現(xiàn)火邓,不由父類實現(xiàn)的任何實例方法
,所以LGPerson的方法列表打印結(jié)果只有sayHello方法
instanceMethod_classToMetaclass
函數(shù)
/**
* 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
函數(shù)
/**
* 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
描述信息里面已經(jīng)說明:如果在傳入的類或者類的父類中沒有找到指定的類方法
椰拒,則返回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
其本質(zhì)就是獲取 元類
的 實例方法
,最終還是會走到 class_getInstanceMethod
, 但是在這里需要注意的一點是:在 getMeta
源碼 中罕伯,如果判斷出cls 是 元類
曲伊,那么就不會
再繼續(xù)往下遞歸查找
,會直接返回 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函數(shù)
IMP class_getMethodImplementation(Class cls, SEL sel)
{
IMP imp;
if (!cls || !sel) return nil;
//查找方法實現(xiàn)
imp = lookUpImpOrNil(nil, sel, cls, LOOKUP_INITIALIZE | LOOKUP_RESOLVER);
//如果沒有找到,則進行消息轉(zhuǎn)發(fā)
if (!imp) {
return _objc_msgForward;
}
return imp;
}
class_getMethodImplementation
主要是返回方法的具體實現(xiàn)
,由源碼
可以看出返回的函數(shù)指針可能是一個指向runtime內(nèi)部的函數(shù)
硅堆,而不一定是方法的實際實現(xiàn)屿储。如果類實例無法響應selector
,則返回的函數(shù)指針
將是運行時消息轉(zhuǎn)發(fā)機制
的一部分
-
0x100001d10
根據(jù)LGPerson
文件渐逃,可以得出LGPerson
類中可以查找
到sayHello
的具體實現(xiàn)够掠,所以返回一個imp函數(shù)指針
的地址 -
0x7fff66861580
根據(jù)類方法存儲在元類
中可知,sayHello
是一個實例方法
茄菊,并不存儲在元類中疯潭,也沒有其任何實現(xiàn),所以進行了消息轉(zhuǎn)發(fā)
- 0x7fff66861580
sayHappy
是一個類方法
面殖,并不存儲在類中竖哩,也沒有其任何實現(xiàn),所以進行了消息轉(zhuǎn)發(fā)
- 0x100001d40 可以在元類中查找到
sayHappy
的具體實現(xiàn)脊僚,所以返回一個imp
函數(shù)指針的地址
總結(jié) :class_getMethodImplementation
:獲取方法的具體實現(xiàn)相叁,如果未查找
到,則進行消息轉(zhuǎn)發(fā)
二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);
打印結(jié)果
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
讓我們先看下源碼在進行結(jié)果分析
-isKindOfClass
源碼解析(實例方法 & 類方法)
//--isKindOfClass---類方法、對象方法
//+ isKindOfClass:第一次比較是 獲取類的元類 與 傳入類對比钝荡,再次之后的對比是獲取上次結(jié)果的父類 與 傳入 類進行對比
+ (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:第一次是獲取對象類 與 傳入類對比街立,如果不相等,后續(xù)對比是繼續(xù)獲取上次 類的父類 與傳入類進行對比
- (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 不相等, 繼續(xù)循環(huán) ,NSObject 的元類的父類為NSObject ,相等 返回1 - re2 0
NSObject -> isa
即 NSObject 的元類 與 NSObject 不相等 返回0 - re3 0
LGPerson -> isa
即LGPerson 的元類
!= LGPerson
,繼續(xù)循環(huán)LGPerson 的元類的父類
根元類 != LGPerson
繼續(xù)根元類 的父類
NSObject != LGPerson
NSObject
的父類nil
!= LGPerson結(jié)束循環(huán)
返回0
- re4 0
LGPerson -> isa 即 LGPerson 的元類
與 LGPerson 不相等 返回0
實例方法
- re5 1 獲取對象的類
NSObject
vs 傳入的類NSObject
相等 - re6 1 獲取對象的類
NSObject
vs 傳入的類NSObjec
t 相等 - re7 1 獲取
對象的類 LGPerson
vs 傳入的類LGPerson
相等 - re8 1 獲取
對象的類 LGPerson
vs 傳入的類LGPerson
相等