没执行dealloc方法但是instrument里又没有检测出内存泄漏

源代码在这里
我觉得我的代码里面至少有两个问题导致内存泄漏:
1.blcok导致的循环引用

self.countDownButton = [[CQCountDownButton alloc] initWithFrame:CGRectMake(90, 90, 150, 30) duration:10 countDownStart:^{
        //------- 倒计时开始 -------//
        NSLog(@"倒计时开始");
    } countDownUnderway:^(NSInteger restCountDownNum) {
        //------- 倒计时进行中 -------//
        [self.countDownButton setTitle:[NSString stringWithFormat:@"再次获取(%ld秒)", restCountDownNum] forState:UIControlStateNormal];
    } countDownCompletion:^{
        //------- 倒计时结束 -------//
        [self.countDownButton setTitle:@"点击获取验证码" forState:UIControlStateNormal];
        self.countDownButton.enabled = YES;
        NSLog(@"倒计时结束");
    }];

2.NSTimer的强引用

/** 控制倒计时的timer */
@property (nonatomic, strong) NSTimer *timer;

视图控制器返回到上一页的时候dealloc方法没有执行,然后我在instrument里面调试,操作半天都没发现内存泄漏,不知道这是什么情况。源代码我已上传但GitHub,希望有大佬可以帮我看看,万分感谢。

阅读 2.5k
1 个回答

1.block循环引用, 你的三个block都是会强引用里面的对象, 应该将self设置为weak断开循环.

__weak SecondViewController *weakSelf = self;
    self.countDownButton = [[CQCountDownButton alloc] initWithFrame:CGRectMake(90, 90, 150, 30) duration:10 countDownStart:^{
        //------- 倒计时开始 -------//
        NSLog(@"倒计时开始");
    } countDownUnderway:^(NSInteger restCountDownNum) {
        //------- 倒计时进行中 -------//
        [weakSelf.countDownButton setTitle:[NSString stringWithFormat:@"再次获取(%ld秒)", restCountDownNum] forState:UIControlStateNormal];
    } countDownCompletion:^{
        //------- 倒计时结束 -------//
        [weakSelf.countDownButton setTitle:@"点击获取验证码" forState:UIControlStateNormal];
        weakSelf.countDownButton.enabled = YES;
        NSLog(@"倒计时结束");
    }];

2.CQCountDownButton置为nil后, 由于timer还在mainRunloop中, 所以timer会继续工作, 应该在停止timer事件.

// 在 CQCountDownButton.m中重写 removeFromSuperview 方法
//- (void)dealloc {
//    [_timer invalidate];
//    _timer = nil;
//}

- (void)removeFromSuperview {
    if ([_timer isValid]) {
        [_timer invalidate];
        _timer = nil;
    }
    [super removeFromSuperview];
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题