1. objc_getClass
通过类名来获取一个类对象,传入 const char *
返回对应的类对象。
- 源码
/***********************************************************************
* objc_getClass. Return the id of the named class. If the class does
* not exist, call _objc_classLoader and then objc_classHandler, either of
* which may create a new class.
* Warning: doesn't work if aClassName is the name of a posed-for class's isa!
**********************************************************************/
Class objc_getClass(const char *aClassName)
{
if (!aClassName) return Nil;
// NO unconnected, YES class handler
return look_up_class(aClassName, NO, YES);
}
示例:
Class c1 = objc_getClass((const char *)"NSObject");
Class c2 = objc_getClass((const char *)"NSObject"
Class c3 = [NSObject class];
NSObject *ojb = [[c1 alloc] init];
NSLog(@"%p, %p, %p", c1, c2 , c3 );
//0x7fff94d1c118, 0x7fff94d1c118, 0x7fff94d1c118
NSLog(@"%p", ojb );
//0x10071c950
示例:
NSObject *instanceClass = [[NSObject alloc] init];
Class classObj = object_getClass(instanceClass);
Class metaclassObj = object_getClass(classObj);
NSLog(@"%p %p %p",instanceClass, classObj, metaclassObj);
//0x100743440 0x7fff94d1c118 0x7fff94d1c0f0
NSLog(@"%p ", [NSObject class]);//0x7fff94d1c118
bool isMeta = class_isMetaClass(metaclassObj);
NSLog(@"metaclassObj : %d ", isMeta);// 1
2. object_getClass
传入一个对象,获取该对象isa指针
指向的对象
。
- 源码
Class object_getClass(id obj)
{
if (obj) return obj->getIsa();
else return Nil;
}
如果传入的是
实例对象instance
,则返回类对象class
,
如果传入的是类对象class
,则返回元类对象meta-class
,
如果传入的是元类对象meta-class
,则返回NSObject(基类)的元类对象meta-class
。
3. class
实例对象、类对象调用class
方法都返回类对象
- (Class)class {
//self->isa
return object_getClass(self);
}
+ (Class)class {
return self;
}
示例:
NSObject *object1 = [[NSObject alloc] init];
Class object2 = object_getClass(object1);
// 0x7fff94d1c118 0x7fff94d1c118 0x7fff94d1c118
NSLog(@"%p %p %p",[NSObject class], [object1 class], [object2 class]);```
网友评论