简体   繁体   中英

ARC - How to get rid of stuff

I just decided to run a test upon suspecting some behavior:

In my view controller I have a new game method which does this:

-(void) newClassicGame {

    if (classicGame!=nil) {
        [classicGame saveStats];
    }

    classicGameController = nil;
    classicGameController = [[RegularGameViewController alloc] initWithPowerMode:NO ];

    classicGame = nil;
    classicGame = [[RegularGame alloc] initWithViewController:classicGameController];

    classicGameController.game = classicGame; // game property is __weak to avoid 
    //retain cycles.

    [classicGame startGame];

}

and to test if objects get destroyed with ARC, in the startGame method of classicGame, I put this:

-(void) startGame
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"once");
        [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(repeat) userInfo:nil repeats:YES];
    });
//other stuff..

}

-(void) repeat {

    NSLog(@"I repeat");

}

for those who are not familiar with dispatch_once method, it's just a method that makes sure that the block gets called exactly once, and no more, during the life time of an application.

I start my app, hit new game and game starts - I see the log "I repeat" repeating every 3 seconds".. Then I go back to the menu and hit new game again. Strangely, the log keeps on repeating, indicating that my classicGame instance is not completely destroyed and the timer is still running somewhere. Any ideas what is happening here?

您创建的计时器保留其目标( 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