简体   繁体   中英

In Objective-C with ARC, can you guarantee the lifetime of associated objects?

I've seen a lot of code that uses associated objects to do cleanup-on-dealloc of an object.

eg NSObject+BlockObservation

Some of this code was written before ARC.

Now, browsing through the issues for ReactiveCocoa, I found this issue: https://github.com/ReactiveCocoa/ReactiveCocoa/pull/580

Quote:

Dealloc disposables are now torn down in a swizzled -dealloc , not as an associated object (which happens later, and can cause use-after-free errors).

So, can we continue to use associated objects for things like automated observation removal under ARC, or is such code broken under ARC?

http://www.opensource.apple.com/source/objc4/objc4-493.9/runtime/objc-runtime-new.mm

shows:

void *objc_destructInstance(id obj) 
{
    if (obj) {
        Class isa_gen = _object_getClass(obj);
        class_t *isa = newcls(isa_gen);

        // Read all of the flags at once for performance.
        bool cxx = hasCxxStructors(isa);
        bool assoc = !UseGC && _class_instancesHaveAssociatedObjects(isa_gen);

        // This order is important.
        if (cxx) object_cxxDestruct(obj);
        if (assoc) _object_remove_assocations(obj);

        if (!UseGC) objc_clear_deallocating(obj);
    }

    return obj;
}

And that bit of code is basically the bulk of the implementation of -[NSObject dealloc] . In other words, the associated objects are more or less released just before your "owner" object is deallocated, so the only things that you should hope functional on those objects are the features NSObject provides.

Fortunately, KVO and NotificationCenter both allow you to deregister by saying your "name (read address)" and being an NSObject, so I would expect everything to be just fine.

I don't think ARC is relevant to that discussion in any way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM