int total = 0; // these are globals..
BOOL dispatchCalled = NO; //
-(void) callDispatch
{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_current_queue(), ^{
dispatchCalled = YES;
NSLog(@"Total, after 300ms, is %i", total);
});
}
-(void)play // this is my "main" method..
{
NSLog(@"app starts running");
[self callDispatch];
while(!dispatchCalled)
{
total++;
}
[self callDispatch];
}
安慰 :
2012-08-02 20:36:05.357 MyProject[8245:1a07] app starts running
2012-08-02 20:36:05.693 MyProject[8245:3d03] Total, after 300ms, is 11513522
2012-08-02 20:36:05.993 MyProject[8245:3d03] Total, after 300ms, is 11513523
当 callDispatch 中包含的方法第一次执行时,while 循环有时间执行 11513522 次。此时,while 循环的条件设置为YES
,while 循环不再执行。但是,它会在确认由调度方法条件更新之前再执行一次。这是为什么?
是不是因为 callDispatch 中包含的方法将与while 循环同时/并行 执行,这可以解释为什么 while 循环需要多一个周期才能确认更新的条件?