質問

Is there any method (like – viewDidLoad) to continuously execute a part of code? I need to be able to check a value on a remote server continuously.

役に立ちましたか?

解決

The way you would do this is to set up an 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
}

The timerWithTimeInterval function is the one that you are interested in, the main things that you need to pass it, as you see above, are the interval at which it will execute the function whose selector you pass it. The time interval is in seconds, so it is currently set to check every second, which is probably way too fast.

他のヒント

Use an NSTimer to execute the same block of code every x seconds. However, I don't think that's what you want, given that it would put a lot of extra load on the server and you might get banned, so there's probably a better way.

apple's page on NSTimer use

You ned to use NSTimer For this:

in your interface declare a NSTimer object like:

NSTimer *timer;

in your .m viewDidLoad method add the below line.

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

In the timerFireMethod method you need to do the server calling and other stuffs.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top