[英]How to use asynchronous data
I'm trying to fetch some data from a remote file. 我正在尝试从远程文件中获取一些数据。 I'm creating an _items array inside the asynchronous request block, which is actually full of data, but when calling the _items anywhere else in my controller is still empty. 我正在异步请求块内创建一个_items数组,该数组实际上充满了数据,但是当调用_items时,控制器中其他位置仍然为空。
I'm not sure but i'm guessing that as the data are loaded asyncronously, when calling _items is still empty. 我不确定,但是我猜测当调用_items仍然为空时,由于数据已异步加载。 So how how can i use the array with data, after the async task is completed? 那么,异步任务完成后,如何将数组与数据一起使用?
- (IBAction)fetchEvent
{
_items = [[NSMutableArray alloc] initWithCapacity:5];
NSString *link = [NSString stringWithFormat:@"url...?id=%@", self.eId];
NSURL *url = [NSURL URLWithString:link];
NSURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
if (data.length > 0 && connectionError == nil)
{
NSDictionary *match = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
NSArray *odds = [match objectForKey:@"odds"];
OddsItem *item;
for ( NSDictionary *books in odds ) {
item = [[OddsItem alloc] init];
item.oddsBook = [odds objectForKey:@"book"];
[_items addObject:item];
}
}
}];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self fetchEvent];
}
mutable data is dangerous in multi thread situation. 在多线程情况下,可变数据很危险。 NSArray is better. NSArray更好。
@property (nonatomic, copy) NSArray *items;
block can capture outside variables but can not modify it directly. 块可以捕获外部变量,但不能直接对其进行修改。 In completion block try this 在完成块中试试这个
if (data.length > 0 && connectionError == nil)
{
NSDictionary *match = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
NSArray *odds = [match objectForKey:@"odds"];
NSMutableArray *items = [[NSMutableArray alloc] initWithCapacity:5];
for ( NSDictionary *books in odds ) {
OddsItem *item = [[OddsItem alloc] init];
item.oddsBook = [odds objectForKey:@"book"];
[items addObject:item];
}
self.items = items;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.