剛剛開始對objective-c進行編程,現在我遇到了無法自行處理的問題。我收到來自異步請求的數據,並嘗試將其解析爲單例,但沒有更改。嘗試在單例中更改變量,但它保持爲空
這就是我想要存儲我的數據
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
這是類,在那裏我從服務器接收數據:
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];
}
這是我打電話請求,並嘗試提供它獨居類:
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
}
也許是因爲你的電話是異步?首先打印什麼'NSLog()'行? – Larme