我的要求是我想每 6 秒调用一次 API 从我的服务器请求一些新信息,所以我编写了如下代码:
MyBackgroundThread(){
while(self.isStop){
[self callMyAPI];
[NSThread sleepfortimeinterval : 6 ];
}
}
但是我今天发现Foundation库提供了一种编写运行循环的方法。所以我可以重写我的代码如下:
MyBackgroundThread(){
NSTimer *timer = [NSTimer timerWithTimeInterval:6 target:self selector:@selector(callMyAPI) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
[timer release];
while (! self.isCancelled) {
BOOL ret = [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
}
但是,我不知道这些是不是比原来的更好的方法来完成我的工作?如果是,为什么?以及如何测试这两种方式之间的效率(或其他属性?)差异?
谢谢!