内存管理-weak

一、weak的作用

  • 测试代码
#import "ViewController.h"
#import "RevanPerson.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

      RevanPerson *personStrong;
    __weak RevanPerson *personWeak;
    __unsafe_unretained RevanPerson *personUnsafe;
    
    NSLog(@"person作用域开始");
    {
        RevanPerson *person = [[RevanPerson alloc] init];
    }
    NSLog(@"person作用域之外");
}

@end
  • 打印输出
2018-07-28 01:52:27.493232+0800 08-weak原理[53096:3349035] person作用域开始
2018-07-28 01:52:27.493488+0800 08-weak原理[53096:3349035] -[RevanPerson dealloc]
2018-07-28 01:52:27.494227+0800 08-weak原理[53096:3349035] person作用域之外
  • 分析
    • 因为person对象是一个局部变量,当一出作用域范围就会被释放,所以会发现[RevanPerson dealloc]输出在“person作用域之外”输出之前打印

使用personStrong引用

  • 测试代码
#import "ViewController.h"
#import "RevanPerson.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    RevanPerson *personStrong;
    __weak RevanPerson *personWeak;
    __unsafe_unretained RevanPerson *personUnsafe;
    
    NSLog(@"person作用域开始");
    {
        RevanPerson *person = [[RevanPerson alloc] init];
        personStrong = person;
    }
    NSLog(@"person作用域之外--%@", personStrong);
    
}

@end
  • 打印输出
2018-07-28 01:58:21.977346+0800 08-weak原理[53173:3353359] person作用域开始
2018-07-28 01:58:21.978652+0800 08-weak原理[53173:3353359] person作用域之外--<RevanPerson: 0x60400000def0>
2018-07-28 01:58:21.979809+0800 08-weak原理[53173:3353359] -[RevanPerson dealloc]
  • 分析
    • 从打印输出发现有了personStrong引用后RevanPerson不会一出作用域就释放

使用personWeak引用

  • 测试代码
#import "ViewController.h"
#import "RevanPerson.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    RevanPerson *personStrong;
    __weak RevanPerson *personWeak;
    __unsafe_unretained RevanPerson *personUnsafe;
    
    NSLog(@"person作用域开始");
    {
        RevanPerson *person = [[RevanPerson alloc] init];
        personWeak = person;
    }
    NSLog(@"person作用域之外--%@", personWeak);
    
}

@end
  • 打印输出
2018-07-28 02:01:54.585997+0800 08-weak原理[53218:3355992] person作用域开始
2018-07-28 02:01:54.586218+0800 08-weak原理[53218:3355992] -[RevanPerson dealloc]
2018-07-28 02:01:54.586402+0800 08-weak原理[53218:3355992] person作用域之外--(null)
  • 分析
    • 从打印输出可以看出,person对象一出作用域就被释放
    • 使用__weak修饰符修饰的personWeak对象原本是指向person对象的,当person对象释放后,personWeak自动被赋值为nil

使用personUnsafe

  • 测试代码
#import "ViewController.h"
#import "RevanPerson.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    RevanPerson *personStrong;
    __weak RevanPerson *personWeak;
    __unsafe_unretained RevanPerson *personUnsafe;
    
    NSLog(@"person作用域开始");
    {
        RevanPerson *person = [[RevanPerson alloc] init];
        personUnsafe = person;
    }
    NSLog(@"person作用域之外--%@", personUnsafe);
    
}

@end
  • 打印输出
2018-07-28 02:06:07.796183+0800 08-weak原理[53264:3358785] person作用域开始
2018-07-28 02:06:07.796368+0800 08-weak原理[53264:3358785] -[RevanPerson dealloc]
崩溃Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
  • 分析
    • person对象一出作用域就被释放
    • 执行NSLog(@"person作用域之外--%@", personUnsafe);发生崩溃,这是因为使用野指针造成的崩溃
    • 使用__unsafe_unretained修饰符修饰的personUnsafe对象,指向person对象,当person对象被释放时,personUnsafe对象并不会被自动赋值为nil

实例小结

  • weak和unsafe_unretained都是弱引用
  • weak和unsafe_unretained执行的对象被释放时,weak修饰的对象会自动被赋值为nil。unsafe_unretained修饰的对象并不会自动赋值为nil
  • weak是安全的弱引用
  • unsafe_unretained是不安全的弱引用

二、weak原理

  • SideTable结构
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);
}
  • weak_table_t弱引用列表结构
/**
 * The global weak references table. Stores object ids as keys,
 * and weak_entry_t structs as their values.
 */
struct weak_table_t {
    weak_entry_t *weak_entries;
    size_t    num_entries;
    uintptr_t mask;
    uintptr_t max_hash_displacement;
};
  • weak_entry_t结构
struct weak_entry_t {
    DisguisedPtr<objc_object> referent;
    union {
        struct {
            weak_referrer_t *referrers;
            uintptr_t        out_of_line_ness : 2;
            uintptr_t        num_refs : PTR_MINUS_2;
            uintptr_t        mask;
            uintptr_t        max_hash_displacement;
        };
        struct {
            // out_of_line_ness field is low bits of inline_referrers[1]
            weak_referrer_t  inline_referrers[WEAK_INLINE_COUNT];
        };
    };

    bool out_of_line() {
        return (out_of_line_ness == REFERRERS_OUT_OF_LINE);
    }

    weak_entry_t& operator=(const weak_entry_t& other) {
        memcpy(this, &other, sizeof(other));
        return *this;
    }

    weak_entry_t(objc_object *newReferent, objc_object **newReferrer)
        : referent(newReferent)
    {
        inline_referrers[0] = newReferrer;
        for (int i = 1; i < WEAK_INLINE_COUNT; i++) {
            inline_referrers[i] = nil;
        }
    }
}

weak注册

runtime会调用objc_initWeak函数,初始化一个新的 weak指针指向对象的地址。objc_initWeak函数会调用objc_storeWeak函数,objc_storeWeak函数的作用是更新指针指向,创建对应的弱引用表

  • 1、objc_initWeak
id
objc_initWeak(id *location, id newObj)
{
    if (!newObj) {
        *location = nil;
        return nil;
    }

    return storeWeak<DontHaveOld, DoHaveNew, DoCrashIfDeallocating>
        (location, (objc_object*)newObj);
}
  • 2、storeWeak
template <HaveOld haveOld, HaveNew haveNew,
          CrashIfDeallocating crashIfDeallocating>
static id 
storeWeak(id *location, objc_object *newObj)
{
    assert(haveOld  ||  haveNew);
    if (!haveNew) assert(newObj == nil);

    Class previouslyInitializedClass = nil;
    id oldObj;
    SideTable *oldTable;
    SideTable *newTable;

    // Acquire locks for old and new values.
    // Order by lock address to prevent lock ordering problems. 
    // Retry if the old value changes underneath us.
 retry:
    if (haveOld) {//如果已经有了weak列表
        oldObj = *location;
        oldTable = &SideTables()[oldObj];
    } else {
        oldTable = nil;
    }
    if (haveNew) {//通过传入obj创建一个weak列表
        newTable = &SideTables()[newObj];
    } else {
        newTable = nil;
    }

    SideTable::lockTwo<haveOld, haveNew>(oldTable, newTable);

    if (haveOld  &&  *location != oldObj) {
        SideTable::unlockTwo<haveOld, haveNew>(oldTable, newTable);
        goto retry;
    }

    // Prevent a deadlock between the weak reference machinery
    // and the +initialize machinery by ensuring that no 
    // weakly-referenced object has an un-+initialized isa.
    if (haveNew  &&  newObj) {
        //获取对象的isa指针
        Class cls = newObj->getIsa();
        //cls没有初始化
        if (cls != previouslyInitializedClass  &&  
            !((objc_class *)cls)->isInitialized()) 
        {
            SideTable::unlockTwo<haveOld, haveNew>(oldTable, newTable);
            //初始化
            _class_initialize(_class_getNonMetaClass(cls, (id)newObj));

            // If this class is finished with +initialize then we're good.
            // If this class is still running +initialize on this thread 
            // (i.e. +initialize called storeWeak on an instance of itself)
            // then we may proceed but it will appear initializing and 
            // not yet initialized to the check above.
            // Instead set previouslyInitializedClass to recognize it on retry.
            previouslyInitializedClass = cls;

            goto retry;
        }
    }

    // Clean up old value, if any.
    if (haveOld) {
        //解除绑定
        weak_unregister_no_lock(&oldTable->weak_table, oldObj, location);
    }

    // Assign new value, if any.
    if (haveNew) {
        newObj = (objc_object *)
            //注册绑定
            weak_register_no_lock(&newTable->weak_table, (id)newObj, location, 
                                  crashIfDeallocating);
        // weak_register_no_lock returns nil if weak store should be rejected

        // Set is-weakly-referenced bit in refcount table.
        if (newObj  &&  !newObj->isTaggedPointer()) {
            newObj->setWeaklyReferenced_nolock();
        }

        // Do not set *location anywhere else. That would introduce a race.
        *location = (id)newObj;
    }
    else {
        // No new value. The storage is not changed.
    }
    
    SideTable::unlockTwo<haveOld, haveNew>(oldTable, newTable);

    return (id)newObj;
}

weak销毁

当一个对象的引用计数为0时,会自动调用dealloc,接下来会执行

  • dealloc

  • _objc_rootDealloc

  • rootDealloc()

  • object_dispose

  • objc_destructInstance

  • clearDeallocating()

  • clearDeallocating_slow

  • weak_clear_no_lock

  • 1、当一个对象的引用计数为0时,会自动调用dealloc

- (void)dealloc {
    _objc_rootDealloc(self);
}
  • 2、_objc_rootDealloc
void _objc_rootDealloc(id obj)
{
    assert(obj);

    obj->rootDealloc();
}
  • 3、rootDealloc()会判断是否是TaggePointer类型,如果是直接返回;再判断isa指针是否是优化过的,这个对象是否有弱指针引用、是否有关联属性、是否有C++的析构函数、是否引用计数存储在SideTable中。如果满足上面的一个条件,那么就进入object_dispose函数,否则直接释放
inline void
objc_object::rootDealloc()
{
    if (isTaggedPointer()) return;  // fixme necessary?
    /*
     判断isa指针
        nonpointer:是否是优化过的
        weakly_referenced:是否有被弱引用指向过,如果没有,释放时会更快
        has_assoc:是否有设置过关联对象,如果没有,释放时会更快
        has_cxx_dtor:是否有C++的析构函数(.cxx_destruct),如果没有,释放的更快
        has_sidetable_rc:引用计数器是否过大无法存储在isa中,如果为1,那么引用计数会存储在一个叫SideTable的类的属性中
     */
    if (fastpath(isa.nonpointer  &&  
                 !isa.weakly_referenced  &&  
                 !isa.has_assoc  &&  
                 !isa.has_cxx_dtor  &&  
                 !isa.has_sidetable_rc))
    {
        assert(!sidetable_present());
        free(this);//直接释放
    } 
    else {
        object_dispose((id)this);
    }
}
  • 4、object_dispose进行释放obj,但是在释放obj之前调用objc_destructInstance方法
id 
object_dispose(id obj)
{
    if (!obj) return nil;

    objc_destructInstance(obj);    
    free(obj);//释放

    return nil;
}
  • 5、objc_destructInstance函数中销毁C++析构函数、移除管理属性
/***********************************************************************
* objc_destructInstance
* Destroys an instance without freeing memory. 
* Calls C++ destructors.
* Calls ARC ivar cleanup.
* Removes associative references.
* Returns `obj`. Does nothing if `obj` is nil.
**********************************************************************/
void *objc_destructInstance(id obj) 
{
    if (obj) {
        // Read all of the flags at once for performance.
        bool cxx = obj->hasCxxDtor();
        bool assoc = obj->hasAssociatedObjects();

        // This order is important.
        if (cxx) object_cxxDestruct(obj);//销毁
        if (assoc) _object_remove_assocations(obj);//移除关联对象
        obj->clearDeallocating();
    }

    return obj;
}
  • 6、clearDeallocating函数,如果isa指针没有进行优化过直接调用sidetable_clearDeallocating函数,否则调用clearDeallocating_slow函数
inline void 
objc_object::clearDeallocating()
{
    //没有优化的isa指针
    if (slowpath(!isa.nonpointer)) {
        // Slow path for raw pointer isa.
        sidetable_clearDeallocating();
    }
    else if (slowpath(isa.weakly_referenced  ||  isa.has_sidetable_rc)) {
        // Slow path for non-pointer isa with weak refs and/or side table data.
        clearDeallocating_slow();
    }

    assert(!sidetable_present());
}
  • 7、clearDeallocating_slow中判断如果有弱引用,调用weak_clear_no_lock函数清除弱引用;如果有引用计数,也清空引用计数
NEVER_INLINE void
objc_object::clearDeallocating_slow()
{
    assert(isa.nonpointer  &&  (isa.weakly_referenced || isa.has_sidetable_rc));

    SideTable& table = SideTables()[this];
    table.lock();
    if (isa.weakly_referenced) {//isa中有弱引用
        //清除弱引用:weak弱引用表、对象本身
        weak_clear_no_lock(&table.weak_table, (id)this);
    }
    if (isa.has_sidetable_rc) {//isa引用计数
        table.refcnts.erase(this);
    }
    table.unlock();
}
  • 8、weak_clear_no_lock函数中,通过对象本身和runtime维护的weak弱引用表找到本对象的weak弱引用表,然后遍历这个对象的weak弱引用表把里面的弱引用对象一一赋值为nil,最后 把本对象的weak弱引用表从runtime维护的weak弱引用表中移除
/** 
 * Called by dealloc; nils out all weak pointers that point to the 
 * provided object so that they can no longer be used.
 * 
 * @param weak_table 
 * @param referent The object being deallocated. 
 */
void 
weak_clear_no_lock(weak_table_t *weak_table, id referent_id) 
{
    objc_object *referent = (objc_object *)referent_id;
    //通过对象本身,和weak弱引用表
    weak_entry_t *entry = weak_entry_for_referent(weak_table, referent);
    if (entry == nil) {
        /// XXX shouldn't happen, but does with mismatched CF/objc
        //printf("XXX no entry for clear deallocating %p\n", referent);
        return;
    }

    // zero out references
    weak_referrer_t *referrers;//存储弱引用对象数组
    size_t count;
    
    if (entry->out_of_line()) {
        referrers = entry->referrers;
        count = TABLE_SIZE(entry);
    } 
    else {
        referrers = entry->inline_referrers;
        count = WEAK_INLINE_COUNT;
    }
    //遍历存储弱引用的数组,把弱引用对象一一赋值为nil
    for (size_t i = 0; i < count; ++i) {
        objc_object **referrer = referrers[i];
        if (referrer) {
            if (*referrer == referent) {
                *referrer = nil;
            }
            else if (*referrer) {
                _objc_inform("__weak variable at %p holds %p instead of %p. "
                             "This is probably incorrect use of "
                             "objc_storeWeak() and objc_loadWeak(). "
                             "Break on objc_weak_error to debug.\n", 
                             referrer, (void*)*referrer, (void*)referent);
                objc_weak_error();
            }
        }
    }
    //把对象的弱引用列表从弱引用列表中移除
    weak_entry_remove(weak_table, entry);
}

小结

  • 注册过程
    在runtime维护的weak弱引用散列表中,obj做为key,弱引用对象的地址组成的数组作为value来进行存储,并且会把isa指针中weakly_referenced设置为true
  • 销毁过程
    obj引用计数为0,调用dealloc,通过isa指针中的weakly_referenced来清空obj对象的weak弱引用列表,首先通过obj对象从runtime维护的散列表中取出obj对应的weak弱引用数组,然后再遍历这个weak弱引用数组,把每一个弱引用对象赋值为nil,之后在将obj对象对应的这个弱引用weak数组从runtime维护的weak散列表中移除
    -参考资料
    iOS 底层解析weak的实现原理(包含weak对象的初始化,引用,释放的分析)
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,589评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,615评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,933评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,976评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,999评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,775评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,474评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,359评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,854评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,007评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,146评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,826评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,484评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,029评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,153评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,420评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,107评论 2 356

推荐阅读更多精彩内容