简体   繁体   中英

Trying to prevent memory leak

I am trying to do some experiment.

- (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");
}

When button will tap it will take 1 second to perform segue and when this button tapped again it will trigger segue twice, so two instance of ViewController will be created.

In instruments I can see two instances but one of them is leaked VC object .

Now what I am trying to do is

-(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);
}

to keep a record of VC objects and try to destroy the second obj, so I can prevent memory leak.

But its not working, how to I can fix it?

- (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");
    }

Wrote by memory, may be compile errors here

If you want to cancel your previous request. My suggestion is using NSObject CancelPreviousRequest method

How to implement:

- (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];
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM