0

有没有什么方法(比如——viewDidLoad)可以连续执行一部分代码?我需要能够连续检查远程服务器上的值。

4

3 回答 3

1

这样做的方法是设置一个 NSTimer。

-(void)startCheckingValue
{
    mainTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(checkValue:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:mainTimer forMode:NSDefaultRunLoopMode];
}

-(void)checkValue:(NSTimer *)mainTimer
{
    //Placeholder Function, this is where you write the code to check your value on the remote server
}

timerWithTimeInterval 函数是您感兴趣的函数,正如您在上面看到的,您需要传递它的主要内容是它将执行您传递它的选择器的函数的时间间隔。时间间隔以秒为单位,因此当前设置为每秒检查一次,这可能太快了。

于 2012-07-24T17:51:06.907 回答
1

使用 NSTimer 每 x 秒执行一次相同的代码块。但是,我认为这不是您想要的,因为它会给服务器带来很多额外的负载并且您可能会被禁止,所以可能有更好的方法。

苹果关于 NSTimer 使用的页面

于 2012-07-24T17:51:27.827 回答
-1

你需要使用NSTimer为此:

在您的界面中声明一个NSTimer对象,例如:

NSTimer *timer;

在您的 .mviewDidLoad方法中添加以下行。

timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];

在该timerFireMethod方法中,您需要执行服务器调用和其他操作。

于 2012-07-24T17:59:45.823 回答