内存管理-weak

2018-07-28  本文已影响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作用域之外

使用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]

使用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)

使用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)

实例小结

二、weak原理

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);
}
/**
 * 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;
};
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函数的作用是更新指针指向,创建对应的弱引用表

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

    return storeWeak<DontHaveOld, DoHaveNew, DoCrashIfDeallocating>
        (location, (objc_object*)newObj);
}
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,接下来会执行

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

    obj->rootDealloc();
}
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);
    }
}
id 
object_dispose(id obj)
{
    if (!obj) return nil;

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

    return nil;
}
/***********************************************************************
* 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;
}
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());
}
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();
}
/** 
 * 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);
}

小结

上一篇 下一篇

猜你喜欢

热点阅读