xcode 如何每隔x次自动调用功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10597719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 00:20:22  来源:igfitidea点击:

How to automatic call function every x time

iosxcodeuilabelnsdata

提问by Vasuta

Possible Duplicate:
How to call function in every “X” minute?

可能的重复:
如何在每“X”分钟调用一次函数?

How to periodically call a certain function?

如何定期调用某个函数?

- (void)viewDidLoad
{ 
    [super viewDidLoad];
    [self checkAlert];   
}



-(void)checkAlert{
    // Server output Alert Note
    NSString *alert_note_hostStr = @"http://www.loxleyintranet.com/MobileApplication/xml/alert_note.php";
    NSData *alert_note_dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:alert_note_hostStr]];
    NSString *alert_note_serverOutput = [[NSString alloc] initWithData:alert_note_dataURL encoding:NSASCIIStringEncoding];

    if ([alert_note_serverOutput isEqualToString:@"0"]) {
        alertImage.hidden = YES;
        alertLabel.hidden = YES;
        underMainBG.hidden = YES;
        alertLabel.text = [NSString stringWithFormat:@"No Alert"];
    }else{    
        alertLabel.text = [NSString stringWithFormat:@"You've Got Note (%@)" ,alert_note_serverOutput];

    }    
}

How can I call [self checkAlert];every xminutes or seconds?

我怎样才能[self checkAlert];每隔x几分钟或几秒钟打电话?

回答by jimpic

Use [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(checkAlert) userInfo:nil repeats:YES];.

使用[NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(checkAlert) userInfo:nil repeats:YES];.

回答by graver

[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(myTimerTick:) userInfo:nil repeats:YES]; // the interval is in seconds...

...then your myTimerTick:method should look like this..

...那么你的myTimerTick:方法应该是这样的..

-(void)myTimerTick:(NSTimer *)timer
{
    if(some_contiditon)
    {
        // Do stuff...
    }
    else
    {
        [timer invalidate]; //to stop and invalidate the timer.
    }
}