我有三个条件要实现,如下所示,
if(condition 1)
{
return true;
}
else
{
if(condition 2 )
{
//after 10 sec delay call condition 3 which will return BOOL value
retutn that BOOL value after 10 sec
}
else
{
return false;
}
}
如何获得BOOL值作为延迟后的返回类型?
我能想到的最简单的方法就是使用块。像这样声明方法:
-(void)methodWithDelay:(void(^)(BOOL result))aCompletion
{
if(condition 1)
{
aCompletion(YES);
}
else
{
if(condition 2 )
{
//after 10 sec delay call condition 3 which will return BOOL value
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
aCompletion(YES/NO);
});
}
else
{
aCompletion(NO);
}
}
}
然后像这样使用:
[self methodWithDelay:^(BOOL result) {
//do what you want with the result
}];
请注意提供的有关块的文档,以及如何避免它们的内存问题。
您可以添加这样的代码:
dispatch_time_t x = dispatch_time(DISPATCH_TIME_NOW, 10.f * NSEC_PER_SEC);
因此,这将延迟10秒。
您可以使用GCD API dispatch_after在延迟一段时间后返回一个BOOL,它占用了延迟时间、队列和一个完成处理程序,您可以在该处理程序中执行指定延迟时间结束后需要执行的代码。
Foe示例-
if(condition 1)
{
return true;
}
else
{
if(condition 2 )
{
//after 10 sec delay call condition 3 which will return BOOL value
//retutn that BOOL value after 10 sec
double delayInSeconds = 10.0;
dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(delayTime, dispatch_get_main_queue(), ^(void){
return YES;//return NO;
});
}
else
{
return false;
}
}
你可以使用倒计时计时器,这样它就不会影响你的UI,延迟后,它会在onFnished上调用你的方法"callYourBooleabMethod()"。
new CountDownTimer(DELAY,Interval) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
callYourBooleabMethod();
}
}.start();