談?wù)?OC 屬性修飾符的本質(zhì)是什么!

屬性修飾符的本質(zhì)

  • assign 修飾符
  • copy 修飾符
  • atomic 修飾符
  • strong 修飾符
  • weak 修飾符
  • weakTable 實現(xiàn)原理

示例代碼
注: 結(jié)合 runtime 源碼,利用匯編反推出每一個修飾符的本質(zhì)
1.使用 lldb 為每一個屬性的 set 方法下斷點
2.分析調(diào)試匯編代碼,找到真正的操作函數(shù)
3.去 runtime 源碼中找到對應(yīng)的源碼

@interface ViewController ()
@property (assign) NSInteger assignProperty;
@property (copy)   NSString *copytext;
@property (strong) NSObject *strongProperty;
@property (weak)   NSObject *weakProperty;
@end
@implementation ViewController
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self test];
}
- (void)test {
    NSObject *obj = [NSObject new];
    self.assignProperty = 100;
    self.copytext = @"text";
    self.strongProperty = obj;
    self.weakProperty = obj;
}
@end

assign 修飾符

Demo`-[ViewController setAssignProperty:]:
    01. 0x102f4def8 <+0>:  sub    sp, sp, #0x20             ; =0x20 
    // 取出指向 _assignProperty 成員相對偏移量的指針
    02. 0x102f4defc <+4>:  adrp   x8, 4
    03. 0x102f4df00 <+8>:  add    x8, x8, #0x328            ; =0x328 
   
    04. 0x102f4df04 <+12>: str    x0, [sp, #0x18]
    05. 0x102f4df08 <+16>: str    x1, [sp, #0x10]
    06. 0x102f4df0c <+20>: str    x2, [sp, #0x8]
    07. 0x102f4df10 <+24>: ldr    x0, [sp, #0x8]
    08. 0x102f4df14 <+28>: ldr    x1, [sp, #0x18]
    // 取出 _assignProperty 成員相對偏移量(ldrsw 讀取一個字(2個byte)的內(nèi)存數(shù)據(jù))
    09. 0x102f4df18 <+32>: ldrsw  x8, [x8]
    // 計算出 _assignProperty 的內(nèi)存地址
    10. 0x102f4df1c <+36>: add    x8, x1, x8
    // 賦值
    11. 0x102f4df20 <+40>: str    x0, [x8]
    12. 0x102f4df24 <+44>: add    sp, sp, #0x20             ; =0x20 
    13. 0x102f4df28 <+48>: ret    
結(jié)論: assign 修飾符沒有做任何操作,本質(zhì)就是得到內(nèi)存空間,直接賦值

copy 修飾符

Demo`-[ViewController setCopytext:]:
    0x100f79f68 <+0>:  sub    sp, sp, #0x30             ; =0x30 
    0x100f79f6c <+4>:  stp    x29, x30, [sp, #0x20]
    0x100f79f70 <+8>:  add    x29, sp, #0x20            ; =0x20 
    0x100f79f74 <+12>: adrp   x8, 4
    0x100f79f78 <+16>: add    x8, x8, #0x32c            ; =0x32c 
    0x100f79f7c <+20>: stur   x0, [x29, #-0x8]
    0x100f79f80 <+24>: str    x1, [sp, #0x10]
    0x100f79f84 <+28>: str    x2, [sp, #0x8]
    0x100f79f88 <+32>: ldr    x1, [sp, #0x10]
    0x100f79f8c <+36>: ldur   x0, [x29, #-0x8]
    0x100f79f90 <+40>: ldrsw  x3, [x8]
    0x100f79f94 <+44>: ldr    x8, [sp, #0x8]
    0x100f79f98 <+48>: mov    x2, x8
    0x100f79f9c <+52>: bl     0x100f7a8c4               ; symbol stub for: objc_setProperty_nonatomic_copy
    0x100f79fa0 <+56>: ldp    x29, x30, [sp, #0x20]
    0x100f79fa4 <+60>: add    sp, sp, #0x30             ; =0x30 
    0x100f79fa8 <+64>: ret 
結(jié)論: 第14行可以明顯看出,copy 修飾符下,編譯器為你調(diào)用了 objc_setProperty_nonatomic_copy, 
    幸運的是它確實就是 runtime 中的源碼
void objc_setProperty_nonatomic_copy(id self, SEL _cmd, id newValue, ptrdiff_t offset)
{
    reallySetProperty(self, _cmd, newValue, offset, false, true, false);
}
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;
        newValue = objc_retain(newValue);
    }
    if (!atomic) {
        oldValue = *slot;
        *slot = newValue;
    } else {
        spinlock_t& slotlock = PropertyLocks[slot];
        slotlock.lock();
        oldValue = *slot;
        *slot = newValue;        
        slotlock.unlock();
    }
    objc_release(oldValue);
}
reallySetProperty 函數(shù)分析:
    1. 檢查成員偏移量是否合法
    2. 計算出成員的地址
    3. 檢查成員是否需要深淺拷貝
    4. 檢查是否需要原子鎖操作
    5. 取出 oldValue, 賦值 newValue
    6. release oldValue
結(jié)論: copy 的本質(zhì)就是編譯器,為你調(diào)用 objc_setProperty_nonatomic_copy 函數(shù)

atomic 修飾符

由 copy 的本質(zhì), 我們可以看出實質(zhì)是調(diào)用了 reallySetProperty 做了一系列操作,
所以這里就不再進行匯編分析,有興趣的可以自己去實踐

strong 修飾符

Demo`-[ViewController setStrongProperty:]:
    0x102271fd4 <+0>:  sub    sp, sp, #0x30             ; =0x30 
    0x102271fd8 <+4>:  stp    x29, x30, [sp, #0x20]
    0x102271fdc <+8>:  add    x29, sp, #0x20            ; =0x20 
    0x102271fe0 <+12>: adrp   x8, 4
    0x102271fe4 <+16>: add    x8, x8, #0x330            ; =0x330 
    0x102271fe8 <+20>: stur   x0, [x29, #-0x8]
    0x102271fec <+24>: str    x1, [sp, #0x10]
    0x102271ff0 <+28>: str    x2, [sp, #0x8]
    0x102271ff4 <+32>: ldr    x0, [sp, #0x8]
    0x102271ff8 <+36>: ldur   x1, [x29, #-0x8]
    0x102271ffc <+40>: ldrsw  x8, [x8]
    0x102272000 <+44>: add    x8, x1, x8
    0x102272004 <+48>: str    x0, [sp]
    0x102272008 <+52>: mov    x0, x8
    0x10227200c <+56>: ldr    x1, [sp]
    0x102272010 <+60>: bl     0x1022728cc               ; symbol stub for: objc_storeStrong
    0x102272014 <+64>: ldp    x29, x30, [sp, #0x20]
    0x102272018 <+68>: add    sp, sp, #0x30             ; =0x30 
    0x10227201c <+72>: ret   
結(jié)論: strong 修飾符下,編譯器為你調(diào)用了 objc_storeStrong 函數(shù), 
    它也是一個 runtime 源碼中的函數(shù)
void objc_storeStrong(id *location, id obj)
{
    id prev = *location;
    if (obj == prev) {
        return;
    }
    objc_retain(obj);
    *location = obj;
    objc_release(prev);
}
objc_storeStrong 函數(shù)分析:
    1. 取出 oldValue, 對比 newValue
    2. retain newValue
    3. 賦值
    4. release oldValue
結(jié)論: 以上可以看出 strong 修飾的成員變量, 本質(zhì)是一個對應(yīng)類型二級指針, 
    且編譯器為我們調(diào)用了 objc_storeStrong 函數(shù)來操作成員變量

weak 修飾符

Demo`-[ViewController setWeakProperty:]:
    0x102272054 <+0>:  sub    sp, sp, #0x40             ; =0x40 
    0x102272058 <+4>:  stp    x29, x30, [sp, #0x30]
    0x10227205c <+8>:  add    x29, sp, #0x30            ; =0x30 
    0x102272060 <+12>: adrp   x8, 3
    0x102272064 <+16>: add    x8, x8, #0x334            ; =0x334 
    0x102272068 <+20>: stur   x0, [x29, #-0x8]
    0x10227206c <+24>: stur   x1, [x29, #-0x10]
    0x102272070 <+28>: str    x2, [sp, #0x18]
    0x102272074 <+32>: ldr    x0, [sp, #0x18]
    0x102272078 <+36>: ldur   x1, [x29, #-0x8]
    0x10227207c <+40>: ldrsw  x8, [x8]
    0x102272080 <+44>: add    x8, x1, x8
    0x102272084 <+48>: str    x0, [sp, #0x10]
    0x102272088 <+52>: mov    x0, x8
    0x10227208c <+56>: ldr    x1, [sp, #0x10]
    0x102272090 <+60>: bl     0x1022728d8               ; symbol stub for: objc_storeWeak
    0x102272094 <+64>: str    x0, [sp, #0x8]
    0x102272098 <+68>: ldp    x29, x30, [sp, #0x30]
    0x10227209c <+72>: add    sp, sp, #0x40             ; =0x40 
    0x1022720a0 <+76>: ret  
結(jié)論: weak 修飾符下,編譯器為你調(diào)用了 objc_storeWeak 函數(shù), 它也是一個 runtime 源碼中的函數(shù)
id objc_storeWeak(id *location, id newObj)
{
    return storeWeak<DoHaveOld, DoHaveNew, DoCrashIfDeallocating>
        (location, (objc_object *)newObj);
}
static id storeWeak(id *location, objc_object *newObj)
{
    // 檢查參數(shù)
    assert(haveOld  ||  haveNew);
    if (!haveNew) assert(newObj == nil);
    Class previouslyInitializedClass = nil;
    id oldObj;
    SideTable *oldTable;
    SideTable *newTable;
    // 檢查新值和舊值
 retry:
    if (haveOld) {
        // 取出舊值
        oldObj = *location;
        // 取出舊值所在的 hashTable
        oldTable = &SideTables()[oldObj];
    } else {
        oldTable = nil;
    }
    if (haveNew) {
        // 分配新值所在的 hashTable
        newTable = &SideTables()[newObj];
    } else {
        newTable = nil;
    }
    // 對 hashTable 加鎖
    SideTable::lockTwo<haveOld, haveNew>(oldTable, newTable);
    // 檢查舊值與 hashTable 中取出的值是否對應(yīng)(hashTable 碰撞容錯機制)
    if (haveOld  &&  *location != oldObj) {
        SideTable::unlockTwo<haveOld, haveNew>(oldTable, newTable);
        goto retry;
    }
    if (haveNew  &&  newObj) {
        // 取出新值的類對象
        Class cls = newObj->getIsa();
        // 檢查類對象是否被初始化
        if (cls != previouslyInitializedClass  &&  
            !((objc_class *)cls)->isInitialized()) 
        {
            SideTable::unlockTwo<haveOld, haveNew>(oldTable, newTable);
            _class_initialize(_class_getNonMetaClass(cls, (id)newObj));
            previouslyInitializedClass = cls;
            goto retry;
        }
    }
    if (haveOld) {
        // 從 hashTable 中移除舊值
        weak_unregister_no_lock(&oldTable->weak_table, oldObj, location);
    }
    if (haveNew) {
        // 向 hashTable 中插入新值
        newObj = (objc_object *)
            weak_register_no_lock(&newTable->weak_table, 
                                    (id)newObj,
                                    location, 
                                    crashIfDeallocating);
        if (newObj  &&  !newObj->isTaggedPointer()) {
            newObj->setWeaklyReferenced_nolock();
        }
        // 給成員變量賦新值
        *location = (id)newObj;
    }
    else {
        // No new value. The storage is not changed.
    }
    // 為 hashTable 開鎖
    SideTable::unlockTwo<haveOld, haveNew>(oldTable, newTable);
    return (id)newObj;
}
結(jié)論: 綜上所述,我們可以得出,weak 修飾的成員變量實際也是一個對應(yīng)類型的二級指針,
    且編譯器為我們調(diào)用了 objc_storeWeak 函數(shù),來操作成員變量和對應(yīng)的hashTable, 
    接下來將繼續(xù)深入 weakTable 實現(xiàn)原理

weakTable 實現(xiàn)原理

alignas(StripedMap<SideTable>) static uint8_t 
    SideTableBuf[sizeof(StripedMap<SideTable>)];
static void SideTableInit() {
    new (SideTableBuf) StripedMap<SideTable>();
}
static StripedMap<SideTable>& SideTables() {
    return *reinterpret_cast<StripedMap<SideTable>*>(SideTableBuf);
}
注: weakTable 是由一個靜態(tài)的 SideTableBuf 對象所維護,其類型為 <StripedMap<SideTable> *>
template<typename T>
class StripedMap {
    enum { CacheLineSize = 64 };
#if TARGET_OS_EMBEDDED
    enum { StripeCount = 8 };
#else
    enum { StripeCount = 64 };
#endif
    struct PaddedT {
        T value alignas(CacheLineSize);
    };
    PaddedT array[StripeCount];
    static unsigned int indexForPointer(const void *p) {
        uintptr_t addr = reinterpret_cast<uintptr_t>(p);
        return ((addr >> 4) ^ (addr >> 9)) % StripeCount;
    }
 public:
    T& operator[] (const void *p) { 
        return array[indexForPointer(p)].value; 
    }
    const T& operator[] (const void *p) const { 
        return const_cast<StripedMap<T>>(this)[p]; 
    }
    .
    .
    .
}
注: StripeMap 是一個散列表,其成員 PaddedT array[StripeCount](這里分為64個桶),
    PaddedT 內(nèi)部維護著 SideTable 類型的對象,
    函數(shù) static unsigned int indexForPointer(const void *p) 將 weak 對象指針的 hash % 64 分發(fā)入桶.
enum HaveOld { DontHaveOld = false, DoHaveOld = true };
enum HaveNew { DontHaveNew = false, DoHaveNew = true };
struct SideTable {
    spinlock_t slock;
    RefcountMap refcnts;
    weak_table_t weak_table;
    SideTable() {
        memset(&weak_table, 0, sizeof(weak_table));
    }
    ~SideTable() {
        _objc_fatal("Do not delete SideTable.");
    }
    void lock() { slock.lock(); }
    void unlock() { slock.unlock(); }
    void forceReset() { slock.forceReset(); }
    // Address-ordered lock discipline for a pair of side tables.
    template<HaveOld, HaveNew>
    static void lockTwo(SideTable *lock1, SideTable *lock2);
    template<HaveOld, HaveNew>
    static void unlockTwo(SideTable *lock1, SideTable *lock2);
};
注: SideTable 中 slock 負責資源的線程安全, 并維護著真正的 weakTable
struct weak_table_t {
    weak_entry_t *weak_entries;
    size_t    num_entries;
    uintptr_t mask;
    uintptr_t max_hash_displacement;
};
/// Adds an (object, weak pointer) pair to the weak table.
id weak_register_no_lock(weak_table_t *weak_table, id referent, 
                         id *referrer, bool crashIfDeallocating);
/// Removes an (object, weak pointer) pair from the weak table.
void weak_unregister_no_lock(weak_table_t *weak_table, id referent, id *referrer);
#if DEBUG
/// Returns true if an object is weakly referenced somewhere.
bool weak_is_registered_no_lock(weak_table_t *weak_table, id referent);
#endif
/// Called on object destruction. Sets all remaining weak pointers to nil.
void weak_clear_no_lock(weak_table_t *weak_table, id referent);

struct weak_entry_t {
    DisguisedPtr<objc_object> referent;
    .
    .
    .
}
注: 這里可以看出 weak_table_t 管理著一個數(shù)組, 每個元素為 <weak_entry_t *>,
    weak_entry_t 才真正存儲著我們需要的 weak 對象容器
    回到函數(shù) static id storeWeak(id *location, objc_object *newObj)
    我們可以看到:
        1.元素移除函數(shù)為 void weak_unregister_no_lock(weak_table_t *weak_table, id referent, id *referrer);
        2.元素插入函數(shù)為 id weak_register_no_lock(weak_table_t *weak_table, id referent, id *referrer, bool crashIfDeallocating);
void weak_unregister_no_lock(weak_table_t *weak_table, id referent_id, 
                        id *referrer_id)
{
    objc_object *referent = (objc_object *)referent_id;
    objc_object **referrer = (objc_object **)referrer_id;
    weak_entry_t *entry;
    if (!referent) return;
    if ((entry = weak_entry_for_referent(weak_table, referent))) {
        remove_referrer(entry, referrer);
        bool empty = true;
        if (entry->out_of_line()  &&  entry->num_refs != 0) {
            empty = false;
        }
        else {
            for (size_t i = 0; i < WEAK_INLINE_COUNT; i++) {
                if (entry->inline_referrers[i]) {
                    empty = false; 
                    break;
                }
            }
        }
        if (empty) {
            weak_entry_remove(weak_table, entry);
        }
    }
    // Do not set *referrer = nil. objc_storeWeak() requires that the 
    // value not change.
}
注: 遍歷數(shù)組找到 weak 對象,根據(jù) num_refs(weak 對象引用計數(shù))進行移除
id weak_register_no_lock(weak_table_t *weak_table, id referent_id, 
                      id *referrer_id, bool crashIfDeallocating)
{
    objc_object *referent = (objc_object *)referent_id;
    objc_object **referrer = (objc_object **)referrer_id;
    if (!referent  ||  referent->isTaggedPointer()) return referent_id;
    // ensure that the referenced object is viable
    bool deallocating;
    if (!referent->ISA()->hasCustomRR()) {
        deallocating = referent->rootIsDeallocating();
    }
    else {
        BOOL (*allowsWeakReference)(objc_object *, SEL) = 
            (BOOL(*)(objc_object *, SEL))
            object_getMethodImplementation((id)referent, 
                                           SEL_allowsWeakReference);
        if ((IMP)allowsWeakReference == _objc_msgForward) {
            return nil;
        }
        deallocating =
            ! (*allowsWeakReference)(referent, SEL_allowsWeakReference);
    }
    if (deallocating) {
        if (crashIfDeallocating) {
            _objc_fatal("Cannot form weak reference to instance (%p) of "
                        "class %s. It is possible that this object was "
                        "over-released, or is in the process of deallocation.",
                        (void*)referent, object_getClassName((id)referent));
        } else {
            return nil;
        }
    }
    // now remember it and where it is being stored
    weak_entry_t *entry;
    if ((entry = weak_entry_for_referent(weak_table, referent))) {
        append_referrer(entry, referrer);
    } 
    else {
        weak_entry_t new_entry(referent, referrer);
        weak_grow_maybe(weak_table);
        weak_entry_insert(weak_table, &new_entry);
    }
    // Do not set *referrer. objc_storeWeak() requires that the 
    // value not change.
    return referent_id;
}
static void weak_entry_insert(weak_table_t *weak_table, weak_entry_t *new_entry)
{
    weak_entry_t *weak_entries = weak_table->weak_entries;
    assert(weak_entries != nil);
    size_t begin = hash_pointer(new_entry->referent) & (weak_table->mask);
    size_t index = begin;
    size_t hash_displacement = 0;
    while (weak_entries[index].referent != nil) {
        index = (index+1) & weak_table->mask;
        if (index == begin) bad_weak_table(weak_entries);
        hash_displacement++;
    }
    weak_entries[index] = *new_entry;
    weak_table->num_entries++;
    if (hash_displacement > weak_table->max_hash_displacement) {
        weak_table->max_hash_displacement = hash_displacement;
    }
}
static void weak_resize(weak_table_t *weak_table, size_t new_size)
{
    size_t old_size = TABLE_SIZE(weak_table);
    weak_entry_t *old_entries = weak_table->weak_entries;
    weak_entry_t *new_entries = (weak_entry_t *)
        calloc(new_size, sizeof(weak_entry_t));
    weak_table->mask = new_size - 1;
    weak_table->weak_entries = new_entries;
    weak_table->max_hash_displacement = 0;
    weak_table->num_entries = 0;  // restored by weak_entry_insert below
    if (old_entries) {
        weak_entry_t *entry;
        weak_entry_t *end = old_entries + old_size;
        for (entry = old_entries; entry < end; entry++) {
            if (entry->referent) {
                weak_entry_insert(weak_table, entry);
            }
        }
        free(old_entries);
    }
}
注: 該函數(shù)負責 weak_table_t 的插入(weak_entry_insert)和擴容(weak_grow_maybe)
    其中 weak_entry_insert 也是采用的散列分布的方式插入元素,使用了一次線性探測法來解決 hash 碰撞問題

github: https://github.com/huxiaoluder
掘金: https://juejin.im/user/5b76e3a3f265da435a484d37
郵箱: huxiaoluder@163.com

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • OC語言基礎(chǔ) 1.類與對象 類方法 OC的類方法只有2種:靜態(tài)方法和實例方法兩種 在OC中,只要方法聲明在@int...
    奇異果好補閱讀 4,532評論 0 11
  • 我是莫希,我正在挑戰(zhàn)【堅持100天日更】,用100天,遇見全新的自己,歡迎你來見證。 這本是昨天應(yīng)該發(fā)的文,但昨日...
    百莫希閱讀 329評論 0 1
  • 文/云夢河谷 前兩天聽了向帥的寫作指導語音,很有收獲,心里也有一些想法,想形成幾篇文章,奈何工作太忙,一直加班沒能...
    小云哥de閱讀 825評論 19 26
  • 三生三世蘭花,共三層,一層為一世,各諭其理,各表其事,世人要慢慢欣賞,慢慢理解其中的玄奧。
    沂蒙居士閱讀 670評論 0 1
  • 想不起是哪一年了,只約莫記得是初夏,我去看望一個朋友。她老家原本在遠鄉(xiāng),在她很小的時候,父母分開了,她和哥哥跟著父...
    昔子今閱讀 753評論 7 5

友情鏈接更多精彩內(nèi)容