Ios 异步调用异步方法
我正在调用checkWeathermethod,然后通过调用storeWeatherIntoDB将其存储到数据库中。storeWeatherIntoDB完成后,它将通过SQLdelegate调用sendWeatherToServer。sendWeatherToServer完成后,我将使用一个变量通知checkWeathermethod 问题:checkWeathermethod如何等待所有这些过程完成,以便返回变量Ios 异步调用异步方法,ios,asynchronous,delegates,synchronous,countdowntimer,Ios,Asynchronous,Delegates,Synchronous,Countdowntimer,我正在调用checkWeathermethod,然后通过调用storeWeatherIntoDB将其存储到数据库中。storeWeatherIntoDB完成后,它将通过SQLdelegate调用sendWeatherToServer。sendWeatherToServer完成后,我将使用一个变量通知checkWeathermethod 问题:checkWeathermethod如何等待所有这些过程完成,以便返回变量 (int)checkWeathermethod--调用-->storeWeath
如果结果在10秒内返回,checkWeathermethod将返回整数。一种可能的解决方案是使用。例如,如果要在
storeWeatherIntoDB
完成后执行代码,可以通过以下方式执行:
- (void)checkWeathermethod {
[self storeWeatherIntoDB:^(int returnCode) {
dispatch_async(dispatch_get_main_queue(), ^{
// When you get here, the weather has been stored on the server.
// E.g. you can now show success or failure here
if (returnCode == 0) {
// OK
}
else {
// Error
}
});
}];
}
- (void)storeWeatherIntoDB:(void(^)(int returnCode))completionBlock {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
// Store weather into db here.
// You can do this even synchronously.
int returnCode = [self storeWeather];
// Call callback
if (completionBlock) {
completionBlock(returnCode);
}
});
}
我需要sendWeatherToServer返回值到checkWeathermethod。这可能吗?当然可以。只需将返回值(例如,
int
)存储在变量中,并将其传递回方法。我将编辑答案以显示这是如何完成的。谢谢。我来看看这个街区。因此,(int)checkWeathermethod不可能返回int?我必须为它使用一个新变量?因为该方法是异步的,所以只有在storeWeatherIntoDB
完成后,您才能知道返回代码。然后,您可以将返回代码存储在一个变量中,例如。但是,如果您需要在代码运行后将其放在别处,只需在checkWeathermethod
中添加一个完成块即可。这将允许您传递返回代码。