ios crash EXC_BAD_ACCESS KERN_INVALID_ADDRESS

后端 未结 3 1756
广开言路
广开言路 2020-12-23 18:46

MyApp works well 98% of the time, but sometimes it crashes. It\'s so random.

The crash report shows the following.

Thread : Crashed: com.apple.main-thr         


        
3条回答
  •  心在旅途
    2020-12-23 19:27

    EXC_BAD_ACCESS KERN_INVALID_ADDRESS crash is not due to memory leak, but due to the attempt to access an deallocated object.

    Example: if you used __weak typeof(self) weakSelf = self; and object has been released before you accessing it inside block you'll got the crash. The reason — access to wrong memory address because object was deallocated.

    To prevent this use __strong typeof(self) strongSelf = self; inside the block. Nil value will be properly handled without crash


    Note: use this code sample for fast work.

    #define weakify(var) __weak typeof(var) AHKWeak_##var = var;
    
    #define strongify(var) \
    _Pragma("clang diagnostic push") \
    _Pragma("clang diagnostic ignored \"-Wshadow\"") \
    __strong typeof(var) var = AHKWeak_##var; \
    _Pragma("clang diagnostic pop")
    

    Usage example:

    weakify(self); // Remove retain cycle
    [self someFunctionWithBlock:^{
        strongify(self); // Make reference to address valid
    
    }];
    

提交回复
热议问题