为什么我对singleton的引用是nil?

时间:2017-10-16 16:40:10

标签: ios objective-c json singleton

我有这段代码:

在我的.h文件中

@property (nonatomic,strong) NSMutableDictionary *allInformation;

在m。文件

我有这段代码......

+ (instancetype)sharedManager {
    static id sharedData = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedData = [[[self class] alloc] init];
    });
    return sharedData;
}

-(void)buildJsonRequest{
    self.allInformation = [[NSMutableDictionary alloc] init];
            [OpenWeatherAPI fetchData:WEATHER_DATA
                           forZipCode:[valueSelected objectForKey:@"ZipCode"]
                           andCountry:countrySelected
                           usingUnits:API_METRIC_UNITS
                          withHandler:^(NSDictionary* weatherData){

                          [[[JsonParser sharedManager]allInformation] setObject:weatherData forKey:@"data"];

            }];

            [OpenWeatherAPI fetchData:FORECAST
                           forZipCode:[valueSelected objectForKey:@"ZipCode"]
                           andCountry:countrySelected
                           usingUnits:API_METRIC_UNITS
                          withHandler:^(NSDictionary* forecastData){

                          [[[JsonParser sharedManager]allInformation] forecastData forKey:@"data2"];

            }];
        }

当我尝试检索单身人士的信息时,总是为零

另一堂课......

- (instancetype)init
{
    self = [super init];
    if (self) {
        NSDictionary *dataJson = [[JsonParser sharedManager]allInformation];
   }
    return self;
}

总是dataJson为零?

我想要一个NSMutableDictionary单例来保存不同的请求,例如:

  • dataJson [0] Json response(NSDictionary)
  • dataJson [1]另一个Json回复(NSDictionary)

1 个答案:

答案 0 :(得分:0)

最后我找到了解决方案=)

这是零,因为我从未正确初始化该属性

这是解决方案

感谢您的时间和帮助!

我创建了这个额外的方法来正确初始化:

-(instancetype)init {

    if ((self = [super init])) {
        self.allInformation = [NSMutableDictionary new];
    }
    return self;
}

现在我的单身人士已存储值

相关问题