Есть ли способ вернуть значение из блока в Objective- C? - PullRequest
0 голосов
/ 15 апреля 2020

Как я уже сказал в заголовке, есть ли способ вернуть значение из блока?

Это PDDokdo class

@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];

To Подводя итог, я хочу, чтобы -(NSString *)getCurrentTemperature возвращал [NSString stringWithFormat:@"%.f°C", round(temp)] в блоке вместо :(, чтобы я мог получить значение из другого класса.

1 Ответ

1 голос
/ 16 апреля 2020

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);
}];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...