Objective C为变量分配字典并访问它

时间:2013-08-26 21:59:19

标签: objective-c variables nsdictionary

我很抱歉再次提出这个问题,但我仍然被卡住了。

我有一个城市物品试图从天气提取器对象中获取天气

@interface WeatherFetcher : NSObject {

}

@property (nonatomic, strong) NSMutableDictionary *weatherData;

- (void)fetchWeather:(NSString *)cityName;
- (void)handleNetworkErorr:(NSError *)error;
- (void)handleNetworkResponse:(NSData *)myData;

@end

这是我将值赋给weatherData

#import "WeatherFetcher.h"

@implementation WeatherFetcher

- (void)fetchWeather:(NSString *)cityName
{
    NSString *urlString = @"http://api.openweathermap.org/data/2.5/weather?q=";
    urlString = [urlString stringByAppendingString:cityName];
    urlString = [urlString stringByAppendingString:@",Aus"];

    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                               if (connectionError)
                               {
                                   [self handleNetworkErorr:connectionError];
                               }
                               else
                               {
                                   [self handleNetworkResponse:data];
                               }
                           }];
}

#pragma mark - Private Failure Methods

- (void)handleNetworkErorr:(NSError *)error
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Network Error" message:@"Please try again later" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];

    [alert show];
}

#pragma mark - Private Success Methods

- (void)handleNetworkResponse:(NSData *)myData
{
    //NSMutableDictionary *data = [NSMutableDictionary dictionary];
    NSMutableDictionary *data = [[NSMutableDictionary alloc] init];

    // now we'll parse our data using NSJSONSerialization
    id myJSON = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:nil];

    // typecast an array and list its contents
    NSDictionary *jsonArray = (NSDictionary *)myJSON;

    //NSLog([jsonArray description]);

    // take a look at all elements in the array
    for (id element in jsonArray) {

        id key = [element description];

        id innerArr = [jsonArray objectForKey:key];

        NSDictionary *inner = (NSDictionary *)innerArr;

        if ([inner conformsToProtocol:@protocol(NSFastEnumeration)]) {

            for(id ele in inner) {

                if ([ele conformsToProtocol:@protocol(NSFastEnumeration)]) {

                    NSDictionary *innerInner = (NSDictionary *)ele;

                    for(id eleEle in innerInner) {

                        id innerInnerKey = [eleEle description];
                        [data setObject:[[inner valueForKey:innerInnerKey] description] forKey:[eleEle description]];
                    }
                }
                else {

                    id innerKey = [ele description];
                    [data setObject:[[inner valueForKey:innerKey] description] forKey:[ele description]];
                }
            }
        }
        else {

            [data setObject:[inner description] forKey:[element description]];
        }
    }

    self.weatherData = data;
    NSLog([self.weatherData description]) **//there is data**
}

@end

然而,每当我从城市对象那里打电话时,我什么也得不回来。

#import <Foundation/Foundation.h>
#import "WeatherFetcher.h"

@interface City : NSObject {

}

@property (nonatomic, strong) NSString *cityName;
@property (nonatomic, strong) NSString *stateName;
@property (nonatomic, strong) UIImage *cityPicture;
@property (nonatomic, strong) NSString *weather;
@property (nonatomic, strong) NSMutableDictionary *weatherData;

-(NSString *)getWeather;

@end

用户按下按钮调用getWeather以获取要在屏幕上显示的字符串值

@implementation City {


}

-(NSString *)getWeather {

    //return self.weather;

    NSString *info = @"";
    WeatherFetcher *weatherFetcher = [[WeatherFetcher alloc] init];
    [weatherFetcher fetchWeather:self.cityName];
    self.weatherData = [weatherFetcher weatherData];

    for (id element in self.weatherData) {

        info = [info stringByAppendingString:[element description]];
        info = [info stringByAppendingString:@"-->"];
        info = [info stringByAppendingString:[self.weatherData valueForKey:[element description]]];
        info = [info stringByAppendingString:@"\n"];
    }

    return info;
}

@end

我在这里做错了什么?

按下按钮时,将调用city类中的getWeather方法,并且我试图在文本区域中显示此字符串。我没有太多使用Objective C的经验,这是我的第一个应用程序,而不是Hello World应用程序。

谢谢!

1 个答案:

答案 0 :(得分:1)

您的WeatherFetcher 异步sendAsynchronousRequest:) - 它设置任务以获取数据,然后在数据之前返回(通常)已经获得。因此,当您在调用weatherData后立即尝试访问fetchWeather:时,它还没有。

您需要重新设计模型以处理异步性 - getWeather不能同步。例如,您可以使fetchWeather:在数据可用时调用完成块并在适当的块中传递getWeather