为什么在滚动表缓慢滚动时获取数据



下面的代码与我与ASI的使用几乎相同,但是现在我正在使用afnetworking。我的猜测是它很慢,因为它在主线程上运行了成功块。我试图将SuccessCallbackqueue设置为一个新队列,但似乎没有起作用。它只是非常慢,没有有效地做到这一点。如何加快速度或确保其在背景线程中运行?

#define kPerPage 10
- (void) pullData {
    NSURL *url = [API homeRecentUrlWithPage:self.currentRecentPage limit:kPerPage];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    dispatch_queue_t requestQueue = dispatch_queue_create("requestQueue", NULL);
    AFJSONRequestOperation *operation;
    operation.successCallbackQueue = requestQueue;
    operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        NSArray* modelArray = [JSON objectForKey:@"models"];
        for (int i = 0; i < [modelArray count]; i++)
        {
            Model *b = [Model alloc];
            b = [b initWithDict:[Model objectAtIndex:i]];
            [self.otherArray addObject:b];
        }
        [_modelTable reloadData];
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"%@", [error userInfo]);
    }];
    [operation start];
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString* identifier = @"ModelTableCell";
    cell = (ModelTableCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[ModelTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellAccessoryNone;
    }
    if([indexPath row] == (self.currentRecentPage-1) * kPerPage + 5) {
        NSLog(@"%d aaa", self.currentRecentPage);
        self.currentRecentPage++;
        [self pullData];
    }

    Model *b = [self.models objectAtIndex:[indexPath row]];
    [cell populateWithModel:b];
    return cell;
}

我认为您不正确地为回调设置队列

您将回调队列分配给操作,但然后创建一个覆盖它的操作。

// You create the queue
dispatch_queue_t requestQueue = dispatch_queue_create("requestQueue", NULL);
// You declare an operation, but you don't create it.
AFJSONRequestOperation *operation;
// You assign the requestQueue to this uninitialised operation
operation.successCallbackQueue = requestQueue;
// You create the operation here, and it overwrites the requestQueue you have set
operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

您应该在之后设置SuccessCallbackqueue >创建操作。

编辑以添加更多

我的阅读更多。使用GCD和Mountain Lion或ios6应用程序,如果您使用ARC,它会照顾队列的内存管理。因此,当您在方法中声明队列并将其分配给仅分配该值的属性(因为在AFNETWORKING中声明了SuccessCallbackqueue属性),然后将队列释放出来,并且操作不起作用,因此剩下一个无效的队列,您将获得不良访问。

因此,解决此问题的方法是在您的控制器中拥有一个ivar,该ivar对队列保持强烈的参考,因此即使操作不保留队列,您的控制器也不会被清理干净从你下方。

最新更新