OC底层原理04-对象的本质

2020-09-10  本文已影响0人  Gomu_iOS

一、 对象的本质

对象的本质是结构体

二、探索方式clang / xcrun

2.1 什么是clang

2.2 clang命令

2.3 什么是xcrun

2.4 xcrun命令

二、探索

2.1 在main.h中创建一个对象GomuPerson

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here..
        GomuPerson *person = [GomuPerson alloc];
    }
    return 0;
}

2.2 用clang生成c++文件

clang -rewrite-objc main.m -o mian.cpp

2.3 打开生成好的main.cpp

image.png

2.4 寻找探索目标GomuPerson,全局搜索🔍

#ifndef _REWRITER_typedef_GomuPerson
#define _REWRITER_typedef_GomuPerson
typedef struct objc_object GomuPerson;
typedef struct {} _objc_exc_GomuPerson;
#endif

struct GomuPerson_IMPL {
    struct NSObject_IMPL NSObject_IVARS;
};

2.4 我们看看GomuPerson的父类NSObject是否也是结构体,全局搜索NSObject_IMPL

#ifndef _REWRITER_typedef_NSObject
#define _REWRITER_typedef_NSObject
typedef struct objc_object NSObject;
typedef struct {} _objc_exc_NSObject;
#endif

struct NSObject_IMPL {
    Class isa;
};

三、拓展知识

3.1 用clang命令把GomuPerson.m 编译成GomuPerson.cpp

3.2 全局搜索GomuPerson,找到GomuPerson_IMPL

struct GomuPerson_IMPL {
    struct NSObject_IMPL NSObject_IVARS;
    NSString * _Nonnull _name;
};

3.3 往下滑一点会发现属性的set,get的现实方法

image.png

3.3 objc4 源码中找objc_setProperty

void objc_setProperty(id self, SEL _cmd, ptrdiff_t offset, id newValue, BOOL atomic, signed char shouldCopy) 
{
    bool copy = (shouldCopy && shouldCopy != MUTABLE_COPY);
    bool mutableCopy = (shouldCopy == MUTABLE_COPY);
    reallySetProperty(self, _cmd, newValue, offset, atomic, copy, mutableCopy);
}

3.4 进入reallySetProperty

static inline void reallySetProperty(id self, SEL _cmd, id newValue, ptrdiff_t offset, bool atomic, bool copy, bool mutableCopy)
{
    if (offset == 0) {
        object_setClass(self, newValue);
        return;
    }

    id oldValue;
    id *slot = (id*) ((char*)self + offset);

    if (copy) {
        newValue = [newValue copyWithZone:nil];
    } else if (mutableCopy) {
        newValue = [newValue mutableCopyWithZone:nil];
    } else {
        if (*slot == newValue) return;
        //: 对新值的retain
        newValue = objc_retain(newValue);
    }

    if (!atomic) {
        oldValue = *slot;
        *slot = newValue;
    } else {
        spinlock_t& slotlock = PropertyLocks[slot];
        slotlock.lock();
        oldValue = *slot;
        *slot = newValue;        
        slotlock.unlock();
    }
    //: 对就值的release
    objc_release(oldValue);
}

3.4 set方法的工厂设计模式

image.png
上一篇 下一篇

猜你喜欢

热点阅读