简体   繁体   English

ARC-如何清除杂物

[英]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: 并测试对象是否被ARC破坏,在classicGame的startGame方法中,我将其放置为:

-(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. 对于那些不熟悉dispatch_once方法的人来说,它只是一种确保在应用程序生命周期中仅一次调用该块的方法,而不会再次调用该块。

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? 我启动我的应用程序,点击新游戏,然后游戏开始-我看到日志“我重复”每3秒重复一次。”然后回到菜单再次点击新游戏。奇怪的是,日志不断重复,表明我的classicGame实例没有完全销毁,计时器仍在某处运行,有什么想法吗?

您创建的计时器保留其目标( self ,游戏),因此至少在计时器无效之前,不会释放游戏对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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