0

下面的代码与我在 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;
}
4

1 回答 1

1

我认为您没有正确设置回调队列

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

// 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 属性),队列将被释放,并且操作不会保留它,所以它是留下一个 NULL 队列,您将获得错误的访问权限。

所以,解决这个问题的方法是在你的控制器中有一个 iVar,它保持对队列的强引用,所以即使操作不保留队列,你的控制器也会,所以它不会从你下面被清理.

于 2012-11-04T05:19:12.213 回答