正如我在标题中所说,有什么方法可以从块中返回值?
这是PDDokdo
类
@implementation PDDokdo
-(NSString *)getCurrentTemperature {
WeatherPreferences * weatherPrefs = [NSClassFromString(@"WeatherPreferences") sharedPreferences];
WATodayAutoupdatingLocationModel *todayModel = [[NSClassFromString(@"WATodayAutoupdatingLocationModel") alloc] init];
[todayModel setPreferences:weatherPrefs];
City *city = todayModel.forecastModel.city;
__block double temp = 0;
__block long long conditionCode = 0;
[[NSClassFromString(@"TWCLocationUpdater") sharedLocationUpdater] updateWeatherForLocation:city.location city:city isFromFrameworkClient:true withCompletionHandler:^{
temp = [[city temperature] celsius];
conditionCode = [city conditionCode];
return [NSString stringWithFormat:@"%.f°C", round(temp)];
}];
return @":(";
}
@end
我希望它在一个块中返回一个值,而不是方法的结尾。
由于PDDokdo
是NSObject
的子类,因此我在另一个类中得到如下结果。
NSString *temperature = [[PDDokdo alloc] getCurrentTemperature];
总而言之,我希望-(NSString *)getCurrentTemperature
在一个块中而不是[NSString stringWithFormat:@"%.f°C", round(temp)]
返回:(
,以便可以从另一个类中获取值。
答案 0 :(得分:3)
getCurrentTemperature
应该返回void
并接受一个块作为参数:
typedef void(^CurrentTemperatureCompletion)(NSString *);
@implementation PDDokdo
-(void)getCurrentTemperature:(CurrentTemperatureCompletion)completion {
WeatherPreferences * weatherPrefs = [NSClassFromString(@"WeatherPreferences") sharedPreferences];
WATodayAutoupdatingLocationModel *todayModel = [[NSClassFromString(@"WATodayAutoupdatingLocationModel") alloc] init];
[todayModel setPreferences:weatherPrefs];
City *city = todayModel.forecastModel.city;
__block double temp = 0;
__block long long conditionCode = 0;
[[NSClassFromString(@"TWCLocationUpdater") sharedLocationUpdater] updateWeatherForLocation:city.location city:city isFromFrameworkClient:true withCompletionHandler:^{
temp = [[city temperature] celsius];
conditionCode = [city conditionCode];
NSString* result = [NSString stringWithFormat:@"%.f°C", round(temp)];
completion(result);
return result;
}];
}
@end
在这种情况下,您无需等待updateWeatherForLocation
完成。
您可以这样称呼它:
[[[PDDokdo alloc] init] getCurrentTemperature:^(NSString * temperature) {
NSLog(@"%@", temperature);
}];