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
根據(jù)以上代碼可以看到不管是對象調用class
方法還是類調用class
方法,得到的都是類對象睛榄,且不是元類對象荣茫,那么class
底層是如何實現(xiàn)的呢?
class
源碼
+ (Class)class {
return self;
}
- (Class)class {
return object_getClass(self);
}
可以看到class
的類方法直接返回調用類的類對象场靴;實例方法調用object_getClass
且參數(shù)為實例對象啡莉。
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)
魄咕,參數(shù)是類名稱的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;
//根據(jù)類對象名稱字符串獲取類對象
cls = objc_getClass (aClassName);
if (!cls)
{
_objc_inform ("class `%s' not linked into application", aClassName);
return Nil;
}
//返回類對象的isa指針指向 即元類對象
return cls->ISA();
}
objc_getClass
源碼 根據(jù)字符串獲取類
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
注意:
不管是根據(jù)斷點源碼還是根據(jù)查看匯編仅乓,在調用isKindOfClass
時并沒有走到NSObject.mm
中的isKindOfClass
對象方法和類方法赖舟,反而走的是objc_opt_isKindOfClass
,這是因為llvm對一些不經常重寫的方法進行了優(yōu)化夸楣,如果重寫了宾抓,則進行msgSend消息發(fā)送流程子漩。
llvm中對部分方法進行轉發(fā)
// 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,則根據(jù)傳入對象的isa獲取到Class cls
石洗,此處如果傳入實例對象則獲取類對象幢泼,如果傳入類對象,則獲取元類讲衫,然后遞歸cls
及其父類缕棵,和otherClass
進行比較。
4. class_getClassMethod
底層實現(xiàn)
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();
}
可以看到涉兽,獲取類方法其實是根據(jù)類找到元類招驴,然后去元類中找實例方法,從而側面證明了枷畏,在OC中區(qū)分的對象方法和類方法别厘,其實在C和C++層面并沒有區(qū)分,都是方法拥诡,只是存儲的位置不一樣触趴。
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;
}
注意:while循環(huán)是從cls開始,遞歸其父類進行查找渴肉,所以如果在元類中查找類方法冗懦,直到根元類仍沒有找到,則因為根元類的父類為根類即
NSObject
仇祭,如果在NSObject
中實現(xiàn)了同名的對象方法披蕉,仍然不會報錯。
如上圖所示前塔,如果調用[LSStudent sleep];
,并不會報unrecognized selector sent to class
的錯誤嚣艇,反而會調用根類中的- (void)sleep
實例方法承冰。