如何在ios中发布我的NSTimer对象?

时间:2014-08-25 12:10:43

标签: ios nstimer

在我的应用程序中,当我从一个视图控制器移动到另一个视图控制器时,我需要释放我的NSTimer。如何在ARC中释放这种类型的对象?我使用下面的代码创建和发布NSTimer但我必须在视图控制器中写这个发布代码?

创造。

- (void)viewDidLoad{
    [super viewDidLoad];
    updateBCK = [NSTimer scheduledTimerWithTimeInterval:(5.0) target:self selector:@selector(changeImage) userInfo:nil repeats:YES];
    [updateBCK fire];
}


-(void)changeImage{

            static int i=0;
            if (i == [myImages count]){
                i=0;
            }
            [UIImageView beginAnimations:nil context:NULL];
            [UIImageView setAnimationDuration:0.6];
            mainBackgroundImageView.alpha=1;
            mainBackgroundImageView.image =[myImages objectAtIndex:i];
            NSLog(@"\n The main screen image is %@",[myImages objectAtIndex:i]);
            [UIImageView commitAnimations];
            i++;
        }

发布。

[updateBCK invalidate];//
    updateBCK = nil;

先谢谢。

5 个答案:

答案 0 :(得分:1)

你应该致电

[timer invalidate];
timer = nil;

您推动视图控制器的位置。如果这是一个问题,您仍然可以在

中调用它
- (void) viewWillDisappear:(BOOL)animated;

此外,您应该在

中初始化它
- (void) viewDidAppear:(BOOL)animated;

这更有意义。

答案 1 :(得分:0)

当你想停止时间时

使用下面的代码

[timer invalidate];  // timer is the name of timer object

答案 2 :(得分:0)

- (IBAction)button:(id)sender {

SecondViewController *second = [[SecondViewController alloc] 
       initWithNibName:@"secondViewController" 
       bundle:nil];


    [self presentViewController:second animated:NO completion:nil];

[self.timer invalidate];  // timer is the name of timer object
timer=nil;//it may work without this line too ;not sure

}

答案 3 :(得分:0)

https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Timers/Articles/usingTimers.html

  

计时器保持对其目标的强引用。这意味着只要计时器保持有效,其目标就不会被释放。作为推论,这意味着计时器的目标尝试在其dealloc方法中使计时器无效是没有意义的 - 只要计时器有效,就不会调用dealloc方法。

答案 4 :(得分:-1)

  

当我从一个视图控制器移动到另一个视图控制器时

然后你应该在delloc中执行此操作,如果你想在你的视图被解雇或释放时做一些清理任务。这是最好的地方,在这种情况下你可以实现它。

-(void)dealloc{

[updateBCK invalidate];//
    updateBCK = nil;

}

希望这有帮助

相关问题