我使用下面的代码等待NSTimer触发
-(void)timer1Fired :(NSTimer *) timer
{
isTriggered=true;
}
//----------------------------------------------
isTriggered=false;
[NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(timer1Fired:)
userInfo:nil
repeats:NO];
int j1 = 0;
while ( !isTriggered && j1 < 1000)
{
[NSThread sleepForTimeInterval: 0.5];
j1++;
}
//continue to do something //b
但看起来NSTimer永远不会被触发
欢迎任何评论
答案 0 :(得分:0)
我不认为[NSThread sleepFortimeInterval]
符合您的期望。你是对的,{500}直到你的500秒长时间循环结束后才会被执行。
此外,isTriggered:
和NSTimer
都是老式的,您应该使用Grand Central Dispatch(替换它们)。 GCD速度更快,使用的资源更少,而且更可靠/更强大。
NSThread
如果您想避免使用低级C API,可以使用dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// do stuff on background thread
dispatch_sync(dispatch_get_main_queue(), ^{
// do stuff on main thread
});
});
和NSOperation
,它们是GCD的高级包装。