IOS - 在异步中创建的数组只返回一个对象

时间:2014-03-19 18:27:56

标签: ios objective-c arrays asynchronous

我真的很难搞清楚这一点。我正在异步地将JSON解析为数组。在异步函数上运行NSLog会打印出一个包含多个对象的数组,这正是我想要的。但是当我在ViewController中的返回数组上运行NSLog时,它只打印出数组的最后一个对象。然后我对它进行计数,实际上,数组中只有一个对象。为什么它只返回一个包含多个对象的数组中的一个对象的数组?以下是我的代码。感谢你提供的任何意见。

异步执行的功能

- (NSArray *)locationsFromJSONFile:(NSURL *)url {
NSURLRequest *request = [NSURLRequest requestWithURL:url
                                             cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                     timeoutInterval:30.0];


NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

NSError *error;
NSMutableDictionary *allTeams = [NSJSONSerialization
                                   JSONObjectWithData:data
                                   options:NSJSONReadingMutableContainers
                                   error:&error];

if( error )
{
    NSLog(@"%@", [error localizedDescription]);
}
else {
    team = allTeams[@"10"];
    for ( NSDictionary *teamArray in team )
    {
        teams = [NSArray arrayWithObjects: teamArray[@"team"], nil];

}
}

return teams;
}

的ViewController

- (void)viewDidLoad
{
[super viewDidLoad];


JSONLoader *jsonLoader = [[JSONLoader alloc] init];
NSURL *url = [[NSBundle mainBundle] URLForResource:@"teams" withExtension:@"json"];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    teams = [jsonLoader locationsFromJSONFile:url];

    int i = [teams count];

    NSString *string = [NSString stringWithFormat:@"%d", i];

    NSLog(@"%@", string);

});
}

1 个答案:

答案 0 :(得分:4)

您需要将对象添加到现有数组,而不是每次都重新启动它

    teams = [NSArray arrayWithObjects: teamArray[@"team"], nil];

应该是

else {
    team = allTeams[@"10"];
    teams = [NSMutableArray array]; 
    for ( NSDictionary *teamArray in team )
    {
        [teams addObject:teamArray[@"team"]];

}

您还使用此代码发送同步请求

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

您应该使用sendAsynchronous方法。操作系统本身可以终止同步请求,并且稍后会导致一些混淆和错误