为什么我的数组被GCD调度清除到主队列?

时间:2013-07-20 03:12:37

标签: ios handler grand-central-dispatch

我有一个appview,它有一个带有viewDidLoad的tableviewcontroller:

- (void)viewDidLoad{
    [super viewDidLoad];
    // begin animating the spinner
    [self.spinner startAnimating];

    [SantiappsHelper fetchUsersWithCompletionHandler:^(NSArray *users) {
        self.usersArray = [NSMutableArray array];
        for (NSDictionary *userDict in users) {
            [self.usersArray addObject:[userDict objectForKey:@"username"]];
        }
        //Reload tableview
        [self.tableView reloadData];
    }];
}

Helper Class方法是这样的:

+(void)fetchUsersWithCompletionHandler:(Handler)handler {

    NSString *urlString = [NSString stringWithFormat:@"http://www.myserver.com/myApp/fetchusers.php"];
    NSURL *url = [NSURL URLWithString:urlString];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];

    [request setHTTPMethod: @"GET"];

    __block NSArray *usersArray = [[NSArray alloc] init];

    //A
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        // Peform the request
        NSURLResponse *response;
        NSError *error = nil;
        NSData *receivedData = [NSURLConnection sendSynchronousRequest:request
                                                     returningResponse:&response
                                                                 error:&error];
        if (error) {
            // Deal with your error
            if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
                NSLog(@"HTTP Error: %d %@", httpResponse.statusCode, error);
                return;
            }
            NSLog(@"Error %@", error);
            return;
        }

        NSString *responseString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];

        usersArray = [NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSASCIIStringEncoding] options:0 error:nil];

        if (handler){
            dispatch_async(dispatch_get_main_queue(), ^{
            handler(usersArray);
            });
        }
    });
}

上面的代码是向我建议的,从我对GCD的了解是有道理的。一切都在主队列上运行,但在NSURLConnection同步调用之前调度到后台队列之前。获取数据后,它会填充usersArray并将其返回主队列。 usersArray被填充,当它测试if处理程序时,它会移动到dispatch_asynch(dispatch_get_main_queue()行。但是当它返回主队列来处理数组字典时,NSArray *用户是空的。应用程序崩溃时出现此错误:

*由于未捕获的异常终止应用程序' NSInvalidArgumentException',原因:' * - [__ NSArrayM insertObject:atIndex:]:对象不能为nil'

如果我将dispatch_async(dispatch_get_main_queue()代码注释掉,如下所示:

if (handler){
            //dispatch_async(dispatch_get_main_queue(), ^{
            handler(usersArray);
            //});
        }

它工作得很好......有点儿,它有点迟钝。为什么这会失败?

1 个答案:

答案 0 :(得分:1)

更换

dispatch_async(dispatch_get_main_queue(),

使用:

dispatch_sync(dispatch_get_main_queue(),

原因:  dispatch_sync将在执行之前等待块完成