有什么方法可以从Objective-C的块中返回值吗?

时间:2020-04-15 16:54:43

标签: objective-c

正如我在标题中所说,有什么方法可以从块中返回值?

这是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

我希望它在一个块中返回一个值,而不是方法的结尾。

由于PDDokdoNSObject的子类,因此我在另一个类中得到如下结果。

NSString *temperature = [[PDDokdo alloc] getCurrentTemperature];

总而言之,我希望-(NSString *)getCurrentTemperature在一个块中而不是[NSString stringWithFormat:@"%.f°C", round(temp)]返回:(,以便可以从另一个类中获取值。

1 个答案:

答案 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);
}];