美文网首页
__weak 关键词的黑魔法

__weak 关键词的黑魔法

作者: 知心哥哥noly | 来源:发表于2015-11-04 15:45 被阅读0次

    Objective C 的 runtime 会维护一个 weak 指针的 hash table ,这个 table 是全局的,所有 object 被销毁的时候,会根据这个 table 来将 weak 指针置为 nil, 而不是野指针

    // https://opensource.apple.com/source/objc4/objc4-647/runtime/objc-weak.mm
    /** 
     * Add new_entry to the object's table of weak references.
     * Does not check whether the referent is already in the table.
     */
    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 index = hash_pointer(new_entry->referent) & (weak_table->mask);
        size_t hash_displacement = 0;
        while (weak_entries[index].referent != nil) {
            index = (index+1) & weak_table->mask;
            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;
        }
    }
    

    相关文章

      网友评论

          本文标题:__weak 关键词的黑魔法

          本文链接:https://www.haomeiwen.com/subject/rioqhttx.html