Objective-C对象dealloc过程

Objective-C对象由dealloc负责内存的释放,在对象释放过程中发生了什么,我们使用源码可以看出释放的过程。

-[NSObject dealloc] 方法会调用_objc_rootDealloc方法,_objc_rootDealloc会调用obj->rootDealloc()方法。

_objc_rootDealloc(id obj)
{
    
    
    ASSERT(obj);

    obj->rootDealloc();
}

_objc_rootDealloc仅仅校验了obj是否为空,然后直接调用obj->rootDealloc()方法。

inline void
objc_object::rootDealloc()
{
    
    
    if (isTaggedPointer()) return;  // fixme necessary?

    if (fastpath(isa().nonpointer                     &&
                 !isa().weakly_referenced             &&
                 !isa().has_assoc                     &&
#if ISA_HAS_CXX_DTOR_BIT
                 !isa().has_cxx_dtor                  &&
#else
                 !isa().getClass(false)->hasCxxDtor() &&
#endif
                 !isa().has_sidetable_rc))
    {
    
    
        assert(!sidetable_present());
        free(this);
    } 
    else {
    
    
        object_dispose((id)this);
    }
}

rootDealloc方法先判断对象是否为taggedPointer指针,如果是直接返回。接下来判断当前对象是否被弱引用,是否有关联对象,是否有自定义的c++析构函数,是否有sidetable引用计数表计数,如果都没有的情况,直接调用free函数就可以了。其他情况需要调用object_dispose方法。


id object_dispose(id obj)
{
    
    
    if (!obj) return nil;

    objc_destructInstance(obj);
    free(obj);

    return nil;
}

object_dispose方法使用objc_destructInstance释放Objective-C相关的内存资源,最后调用free释放其他内存资源。这里的核心是objc_destructInstance方法。

void *objc_destructInstance(id obj)
{
    
    
    if (obj) {
    
    
        bool cxx = obj->hasCxxDtor();
        bool assoc = obj->hasAssociatedObjects();

        if (cxx) object_cxxDestruct(obj);
        if (assoc) _object_remove_associations(obj, /*deallocating*/true);
        obj->clearDeallocating();
    }

    return obj;
}

objc_destructInstance里面判断了当前对象是否有C++析构函数,是否有关联对象。存在关联对象的时候,查找相应的Map然后移除关联对象。最后调用clearDeallocating完成释放对象的收尾工作。

inline void 
objc_object::clearDeallocating()
{
    
    
    if (slowpath(!isa().nonpointer)) {
    
    
        sidetable_clearDeallocating();
    }
    else if (slowpath(isa().weakly_referenced  ||  isa().has_sidetable_rc)) {
    
    
        clearDeallocating_slow();
    }

    assert(!sidetable_present());
}

nonpointer代表开启了isa指针优化,优化的指针和未优化的指针区别是优化的指针增加了ISA_BITFIELD,用来表示当前记录当前对象有没有弱引用,有没有关联对象等信息。

clearDeallocating方法调用sidetable_clearDeallocating方法进一步处理对象释放过程。

objc_object::sidetable_clearDeallocating()
{
    
    
    SideTable& table = SideTables()[this];

    table.lock();
    RefcountMap::iterator it = table.refcnts.find(this);
    if (it != table.refcnts.end()) {
    
    
        if (it->second & SIDE_TABLE_WEAKLY_REFERENCED) {
    
    
            weak_clear_no_lock(&table.weak_table, (id)this);
        }
        table.refcnts.erase(it);
    }
    table.unlock();
}

sidetable_clearDeallocating方法首先获取的SideTable,SideTable是引用计数表,同时也持有了弱引用表。如果当前对象没有被弱引用,方法会直接返回。如果当前对象有被弱引用,调用weak_clear_no_lock移除弱引用,对应的weak指针会被置为nil。

至此,一个Objective-C对象的释放过程就结束了。

猜你喜欢

转载自blog.csdn.net/u011608357/article/details/128069199