如何在同一方法满足某些条件后使计时器无效?

时间:2012-07-11 13:12:58

标签: iphone objective-c ios xcode nstimer

您好我正试图在我的iPhone应用程序中显示自定义进度条,因为我正在编写一种方法来增加进度条值,一旦它的值变为100%,那么我需要使我的计时器无效,我需要停止此递归并显示下一个viewController。 我的代码片段如下所示,

-(void)progressNextValue
{
    progressValue += 1.0f;
    if(progressValue >= progress.maxValue){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"end" message:@"TimeOut!!!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        NSLog(@"Time Out!!!!");
        [mytimer invalidate];
        Second *sec = [[Second alloc] initWithNibName:@"Second" bundle:nil];
        [self.view addSubview:sec.view];    
    }

    progress.currentValue = progressValue;
    mytimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(progressNextValue) userInfo:nil repeats:YES];

}

- (void)viewDidLoad
{
    [super viewDidLoad];
    progress.maxValue = 100.0f;    
    [self progressNextValue];
}

此处即使我的progressValue = progress.maxValuemytimer未获得无效。

提前感谢任何帮助。

4 个答案:

答案 0 :(得分:2)

此代码导致问题,

mytimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(progressNextValue) userInfo:nil repeats:YES];

每次使用重复创建计时器时,就会出现问题。

从任何其他方法调用progressNextValue方法:

-(void)tempMethod

    mytimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(progressNextValue) userInfo:nil repeats:YES];
}

或者只是来自:

- (void)viewDidLoad
{
    [super viewDidLoad];
    progress.maxValue = 100.0f;    
    mytimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(progressNextValue) userInfo:nil repeats:YES];
}

答案 1 :(得分:2)

无论何时运行方法,您都在设置计时器。添加一个return语句,或将timer实例化放在else语句中。

例如:

-(void)progressNextValue
{
    progressValue += 1.0f;
    if(progressValue >= progress.maxValue){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"end" message:@"TimeOut!!!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        NSLog(@"Time Out!!!!");
        [mytimer invalidate];
        Second *sec = [[Second alloc] initWithNibName:@"Second" bundle:nil];
        [self.view addSubview:sec.view];    
    } else {
        // Move this line inside the else statements so that it only gets run if 
        // the progress bar is not full.
        mytimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(progressNextValue) userInfo:nil repeats:YES];
    }

    progress.currentValue = progressValue;
}

答案 2 :(得分:0)

要使计时器无效,您需要致电[myTimer invalidate]。你做了什么。但就我所见,myTimer并未保留。所以当你分配它时retain,当你使它失效时release

希望这有帮助。

干杯!

答案 3 :(得分:0)

而不是在progressNextValue内调用您的计时器,而是在viewDidLoad(或您想要启动它的其他地方)中调用它。保留对计时器的引用(在页面顶部放置NSTimer *t),然后在满足条件时[t invalidate];

问题是当你在'progressNextValue'中调用你的计时器时你会告诉它重复,所以在那里使计时器失效并没有多大作用(因为你有多个计时器)。