我使用下面的代码等待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永远不会被触发
欢迎您的评论
发布于 2012-10-31 12:25:32
我不认为[NSThread sleepFortimeInterval]做了你期望它做的事情。你说得对,直到500秒长的while循环结束后,isTriggered:才会被执行。
此外,NSTimer和NSThread都是老式的,您应该使用中央调度来代替它们(以取代它们)。GCD速度更快,使用的资源更少,而且更可靠/更强大。
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
});
});如果您希望避免使用低级can,可以使用NSOperation和NSOperationQueue,它们是GCD的高级包装器。
https://stackoverflow.com/questions/13151047
复制相似问题