试图防止内存泄漏

时间:2016-10-25 10:19:43

标签: ios objective-c memory-leaks viewcontroller

我正在尝试做一些实验。

- (IBAction)btn1Action:(id)sender {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        [self performSegueWithIdentifier:@"popvc2id" sender:self];
    });

    NSLog(@"TAP");
}

当按钮点击时,将需要1秒钟来执行segue,当再次点击此按钮时,它将触发两次segue,因此将创建两个ViewController实例。

在乐器中,我可以看到两个实例,但其中一个是leaked VC object

现在我要做的是

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    VC2 *vc2 = [segue destinationViewController];
    [ary addObject:vc2];
    if(ary.count > 1) {
        VC2 *vc = (VC2*)ary[1];
        vc = nil;
        [ary removeObjectAtIndex:1];
    }
    [ary removeAllObjects];
    NSLog(@"-> %@", vc2);
}

保留VC objects的记录并尝试销毁第二个obj,这样我就可以防止内存泄漏。

但它不起作用,我该如何解决?

2 个答案:

答案 0 :(得分:1)

- (IBAction)btn1Action:(id)sender {
        __block UIButton * btn = (UIButton*) sender;

        btn.enabled = NO;

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            [self performSegueWithIdentifier:@"popvc2id" sender:self];
            btn.enabled = YES;
        });


        NSLog(@"TAP");
    }

通过内存写,可能是编译错误

答案 1 :(得分:1)

如果您想取消之前的请求。我的建议是使用NSObject CancelPreviousRequest方法

如何实施:

- (IBAction)btn1Action:(id)sender { 
   [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayedAction) object:nil];
   [self performSelector:@selector(delayedAction) withObject:nil afterDelay:1];
}

-(void)delayedAction{
  dispatch_async(dispatch_get_main_queue(), ^{
    [self performSegueWithIdentifier:@"popvc2id" sender:self];
  });
}