通过编译查看对象的本质
研究OC对象的底层结构可以通过将OC对象代码编译成C++代码来进行分析,然后结合源码学习。
首先创建一个demo,在main.c创建一个对象,代码如下:
@interface MyObject : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) int age;
@end
@implementation MyObject
@end
int main(int argc, char * argv[]) {
MyObject *object = [[MyObject alloc] init];
object.name = @"LN";
object.age = 18;
}
通过xcrun -sdk iphonesimulator clang -arch arm64 -rewrite-objc main.m -o main.cpp命令将main.c文件编译成C++代码文件main.cpp。打开,找到MyObject相关的代码:
extern "C" unsigned long OBJC_IVAR_$_MyObject$_name;
extern "C" unsigned long OBJC_IVAR_$_MyObject$_age;
struct MyObject_IMPL {
struct NSObject_IMPL NSObject_IVARS;
int _age;
NSString *_name;
};
// @property (nonatomic, copy) NSString *name;
// @property (nonatomic, assign) int age;
/* @end */
// @implementation MyObject
static NSString * _I_MyObject_name(MyObject * self, SEL _cmd) { return (*(NSString **)((char *)self + OBJC_IVAR_$_MyObject$_name)); }
extern "C" __declspec(dllimport) void objc_setProperty (id, SEL, long, id, bool, bool);
static void _I_MyObject_setName_(MyObject * self, SEL _cmd, NSString *name) { objc_setProperty (self, _cmd, __OFFSETOFIVAR__(struct MyObject, _name), (id)name, 0, 1); }
static int _I_MyObject_age(MyObject * self, SEL _cmd) { return (*(int *)((char *)self + OBJC_IVAR_$_MyObject$_age)); }
static void _I_MyObject_setAge_(MyObject * self, SEL _cmd, int age) { (*(int *)((char *)self + OBJC_IVAR_$_MyObject$_age)) = age; }
// @end
int main(int argc, char * argv[]) {
MyObject *object = ((MyObject *(*)(id, SEL))(void *)objc_msgSend)((id)((MyObject *(*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("MyObject"), sel_registerName("alloc")), sel_registerName("init"));
((void (*)(id, SEL, NSString *))(void *)objc_msgSend)((id)object, sel_registerName("setName:"), (NSString *)&__NSConstantStringImpl__var_folders_kz_91163dcd57j_zw_xyry904bc0000gn_T_main_0e80b4_mi_0);
((void (*)(id, SEL, int))(void *)objc_msgSend)((id)object, sel_registerName("setAge:"), 18);
}
可以看到实际上MyObject在编译时被转换成结构体MyObject_IMPL,由此可知MyObject的本质是一个结构体。MyObject_IMPL里面除了自身的两个属性name和age之外,还有继承自NSObject的属性NSObject_IVARS, NSObject_IVARS就是NSObject的实例变量集,其实里面就是一个isa。通过源码查看NSObject的信息:
@interface NSObject <NSObject> {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-interface-ivars"
Class isa OBJC_ISA_AVAILABILITY;
#pragma clang diagnostic pop
}
简化就是:
@interface NSObject <NSObject> {
Class isa;
}
对象的基础objc_object
对象的底层结构就是一个结构体objc_object。objc_object是所有对象的根对象。类本身也是个对象,它的底层结构objc_class也是继承自objc_object的。那首先我们来看一下objc_object到底长什么样:
struct objc_object {
private:
isa_t isa;
public:
// ISA() assumes this is NOT a tagged pointer object
Class ISA();
// rawISA() assumes this is NOT a tagged pointer object or a non pointer ISA
Class rawISA();
// getIsa() allows this to be a tagged pointer object
Class getIsa();
uintptr_t isaBits() const;
// initIsa() should be used to init the isa of new objects only.
// If this object already has an isa, use changeIsa() for correctness.
// initInstanceIsa(): objects with no custom RR/AWZ
// initClassIsa(): class objects
// initProtocolIsa(): protocol objects
// initIsa(): other objects
void initIsa(Class cls /*nonpointer=false*/);
void initClassIsa(Class cls /*nonpointer=maybe*/);
void initProtocolIsa(Class cls /*nonpointer=maybe*/);
void initInstanceIsa(Class cls, bool hasCxxDtor);
// changeIsa() should be used to change the isa of existing objects.
// If this is a new object, use initIsa() for performance.
Class changeIsa(Class newCls);
bool hasNonpointerIsa();
bool isTaggedPointer();
bool isBasicTaggedPointer();
bool isExtTaggedPointer();
bool isClass();
// object may have associated objects?
bool hasAssociatedObjects();
void setHasAssociatedObjects();
// object may be weakly referenced?
bool isWeaklyReferenced();
void setWeaklyReferenced_nolock();
// object may have -.cxx_destruct implementation?
bool hasCxxDtor();
// Optimized calls to retain/release methods
id retain();
void release();
id autorelease();
// Implementations of retain/release methods
id rootRetain();
bool rootRelease();
id rootAutorelease();
bool rootTryRetain();
bool rootReleaseShouldDealloc();
uintptr_t rootRetainCount();
// Implementation of dealloc methods
bool rootIsDeallocating();
void clearDeallocating();
void rootDealloc();
private:
void initIsa(Class newCls, bool nonpointer, bool hasCxxDtor);
// Slow paths for inline control
id rootAutorelease2();
uintptr_t overrelease_error();
#if SUPPORT_NONPOINTER_ISA
// Unified retain count manipulation for nonpointer isa
id rootRetain(bool tryRetain, bool handleOverflow);
bool rootRelease(bool performDealloc, bool handleUnderflow);
id rootRetain_overflow(bool tryRetain);
uintptr_t rootRelease_underflow(bool performDealloc);
void clearDeallocating_slow();
// Side table retain count overflow for nonpointer isa
void sidetable_lock();
void sidetable_unlock();
void sidetable_moveExtraRC_nolock(size_t extra_rc, bool isDeallocating, bool weaklyReferenced);
bool sidetable_addExtraRC_nolock(size_t delta_rc);
size_t sidetable_subExtraRC_nolock(size_t delta_rc);
size_t sidetable_getExtraRC_nolock();
#endif
// Side-table-only retain count
bool sidetable_isDeallocating();
void sidetable_clearDeallocating();
bool sidetable_isWeaklyReferenced();
void sidetable_setWeaklyReferenced_nolock();
id sidetable_retain();
id sidetable_retain_slow(SideTable& table);
uintptr_t sidetable_release(bool performDealloc = true);
uintptr_t sidetable_release_slow(SideTable& table, bool performDealloc = true);
bool sidetable_tryRetain();
uintptr_t sidetable_retainCount();
#if DEBUG
bool sidetable_present();
#endif
};
通过源码可以发现,对象的底层方法还是很多的。许多关于retain、release的内存管理方法,还能判断是否是弱引用,还能判断是否是关联对象,方便了引用计数管理。当然还有很多关于isa的方法和isa指针。
isa指针
从源码可以看到,结构体objc_object唯一的属性是isa,这个isa是用来存储类指针的。对象的方法列表、缓存等信息都是存储在类结构中。所以对象需要通过isa关联类,以便访问类结构。isa在对象创建时被初始化。(点击了解对象创建流程):
inline void
objc_object::initIsa(Class cls, bool nonpointer, UNUSED_WITHOUT_INDEXED_ISA_AND_DTOR_BIT bool hasCxxDtor)
objc_object类底层结构objc_class的基类
类也是对象,类的底层结构objc_class是继承自objc_object:
struct objc_class : objc_object {
objc_class(const objc_class&) = delete;
objc_class(objc_class&&) = delete;
void operator=(const objc_class&) = delete;
void operator=(objc_class&&) = delete;
// Class ISA;
Class superclass;
cache_t cache; // formerly cache pointer and vtable
class_data_bits_t bits; // class_rw_t * plus custom rr/alloc flags
......
}
关于更多类的详细的底层结构,可以参考OC类的底层结构objc_class。
protocol底层结构也继承自objc_object
objc_object底层的存在形式也是对象,所以我们才可以像对象一样使用protocol。
struct protocol_t : objc_object {
const char *mangledName;
struct protocol_list_t *protocols;
method_list_t *instanceMethods;
method_list_t *classMethods;
method_list_t *optionalInstanceMethods;
method_list_t *optionalClassMethods;
property_list_t *instanceProperties;
uint32_t size; // sizeof(protocol_t)
uint32_t flags;
// Fields below this point are not always present on disk.
const char **_extendedMethodTypes;
const char *_demangledName;
property_list_t *_classProperties;
const char *demangledName();
const char *nameForLogging() {
return demangledName();
}
bool isFixedUp() const;
void setFixedUp();
bool isCanonical() const;
void clearIsCanonical();
# define HAS_FIELD(f) ((uintptr_t)(&f) < ((uintptr_t)this + size))
bool hasExtendedMethodTypesField() const {
return HAS_FIELD(_extendedMethodTypes);
}
bool hasDemangledNameField() const {
return HAS_FIELD(_demangledName);
}
bool hasClassPropertiesField() const {
return HAS_FIELD(_classProperties);
}
# undef HAS_FIELD
const char **extendedMethodTypes() const {
return hasExtendedMethodTypesField() ? _extendedMethodTypes : nil;
}
property_list_t *classProperties() const {
return hasClassPropertiesField() ? _classProperties : nil;
}
};
网友评论