Hacker News new | ask | show | jobs
by e28eta 4587 days ago
I disagree with your mistake #1, and therefore also with the second one. In ARC, dealloc is done eagerly. So, I don't have a problem with unsubscribing in dealloc.

I dislike that receiving the notification mutates global state though. I can't clearly articulate it, but that's why I think the caller should have explicit control over when the behavior is active. I think notification subscriptions that last for the lifetime of the object should probably be related to the object's internal state.

Finally, I went to the clang docs regarding timing of dealloc, and as I read it, they shoot for immediate deallocation, but let it slide for local variables:

    Precise lifetime semantics
    
    In general, ARC maintains an invariant that a retainable object pointer
    held in a __strong object will be retained for the full formal lifetime
    of the object. Objects subject to this invariant have precise
    lifetime semantics.
    
    By default, local variables of automatic storage duration do
    not have precise lifetime semantics. Such objects are simply strong
    references which hold values of retainable object pointer type,
    and these values are still fully subject to the optimizations
    on values under local control.
    
    Rationale
    Applying these precise-lifetime semantics strictly would be prohibitive.
    Many useful optimizations that might theoretically decrease the
    lifetime of an object would be rendered impossible. Essentially,
    it promises too much.

    A local variable of retainable object owner type and automatic storage
    duration may be annotated with the objc_precise_lifetime attribute to
    indicate that it should be considered to be an object with precise lifetime
    semantics.
    
    Rationale
    Nonetheless, it is sometimes useful to be able to force an object to
    be released at a precise time, even if that object does not appear
    to be used. This is likely to be uncommon enough that the syntactic
    weight of explicitly requesting these semantics will not be burdensome,
    and may even make the code clearer.