美文网首页
内存管理-weak

内存管理-weak

作者: 紫荆秋雪_文 | 来源:发表于2018-07-28 10:12 被阅读21次

一、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对象的初始化,引用,释放的分析)

相关文章

  • iOS内存管理详解

    目录 block内存管理 autorelease内存管理 weak对象内存管理 NSString内存管理 new、...

  • Swift中的内存管理

    1、内存管理,weak和unowned2、@autoreleasepool3、C 指针内存管理 1、内存管理,we...

  • iOS内存管理指北

    文章目录 一.内存管理准则 二.属性内存管理修饰符全解析 三.block中的weak和strong 四.weak是...

  • delegate的内存管理属性是weak还是assign

    ARC引入strong和weak两个内存管理属性(以及__strong, __weak, __unsafe_unr...

  • 内存管理-weak

    一、weak的作用 测试代码 打印输出 分析因为person对象是一个局部变量,当一出作用域范围就会被释放,所以会...

  • _weak typeof(self) weakSelf = s

    _weak typeof(self) weakSelf = self; (一)内存管理原则 1、默认strong,...

  • iOS开发OC属性关键字

    内存管理常用几种:assign、strong、weak、copyassign适用于基本数据类型,weak适用于NS...

  • _weak typeof(self) weakSelf = se

    原文地址 关于 _weak typeof(self) weakSelf = self; (一)内存管理原则1、默认...

  • 内存管理 之 Weak

    1、实例 从结果可以看出, 使用__strong修饰person1对象(创建对象默认被Strong修饰),要等到离...

  • 循环引用

    // 内存管理,weak 和 unowoned // ARC // 下面是会造成循环引用 class A: NSO...

网友评论

      本文标题:内存管理-weak

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