Try to change variable in singleton but it stays nullable

Viewed 55

Just started programming on objective-c and now i have issue with which can't deal by myself. I'm receiving data from asynchronous request and try to delver it to singleton, but it's not changed.

This is where i'm trying to store my data
Data.h

#import <Foundation/Foundation.h>
@interface Data : NSObject
@property (nonatomic, strong) NSDictionary *products;
-(void)setProducts:(NSDictionary *)value;
@end

Data.m

#import "Data.h"

@implementation Data

+(Data *)sharedInstance
{
    static Data *_sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _sharedInstance = [[Data alloc] init];
    });
    return _sharedInstance;
}

- (id)init {
    self = [super init];
    if ( self )
    {
        _products = [[NSDictionary alloc] init];
    }
    return self;
}

@end

This is the class, where i'm receiving data from server:
ConnectionService.m

- (void)getProductsWithCompletion:(void (^)(NSDictionary *products))completion
{
    NSString *urlString = [NSString stringWithFormat:@"serverurl", [[AppDelegate instance]getUrl]];
    NSURL *url = [NSURL URLWithString:urlString];

    NSURLSessionDataTask *getData = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
        NSString *rawJson = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSDictionary *value = [rawJson JSONValue];
        completion(value);
    }];
    [getData resume];
}

This is the class where i'm calling request and try to deliver it to singleton:
viewController.m

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:YES];
    [[ConnectionService instance] getProductsWithCompletion:^(NSDictionary *products) {
        [Data sharedInstance].products = products;
        NSLog(@"products: %@", [[Data sharedInstance] products]);//all is working, products contains data
    }];
    // checking received data 
    NSDictionary *tmp = [[Data sharedInstance] products];
    NSLog(@"tmp: %@", tmp); //now it's null
}
2 Answers
Related