retainCount in blocks show extrange behavior

前端 未结 2 881
挽巷
挽巷 2021-01-26 22:04

I got the this code in a class:

- (void)cancel {
    if (_cancelBlock)
        _cancelBlock();
}
- (void)overrideCancelWithBlock:(void(^)(void))cancelBlock {
            


        
相关标签:
2条回答
  • 2021-01-26 22:43

    and the documentation for retainCount says this:

    Important: This method is typically of no value in debugging memory management issues. Because any number of framework objects may have retained an object in order to hold references to it, while at the same time autorelease pools may be holding any number of deferred releases on an object, it is very unlikely that you can get useful information from this method.

    To understand the fundamental rules of memory management that you must abide by, read “Memory Management Rules”. To diagnose memory management problems, use a suitable tool:

    The LLVM/Clang Static analyzer can typically find memory management problems even before you run your program.
    The Object Alloc instrument in the Instruments application (see Instruments User Guide) can track object allocation and destruction.
    Shark (see Shark User Guide) also profiles memory allocations (amongst numerous other aspects of your program).

    To answer your question: Only apple might know why the retainCount at this point is like it is.

    0 讨论(0)
  • 2021-01-26 22:43
    _cancelBlock = [[cancelBlock copy] retain];
    

    That over-retains the block; just -copy it.


    Since Blocks can change form at runtime based upon actions taken and change type at compile time based on implementation details, the various Block classes generally treat retainCount as the nonsense generator that it is. In some cases, this will mean returning 1 always.

    Note that a retainCount of zero is a logical impossibility in all cases.

    0 讨论(0)
提交回复
热议问题