gpt4 book ai didi

ios - UITableView - AFNetworking 后台操作卡住滚动

转载 作者:行者123 更新时间:2023-11-29 03:37:32 25 4
gpt4 key购买 nike

我有一个带有 UITableViewController 的示例应用程序。

与 facebook 新闻源一样,该应用程序应该下载第一次 X 新闻,然后随着用户滚动逐渐获取新闻。

这是我的实现:

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{

if (indexPath.row == self.newsList.count-PADDLE_BEFORE_FETCHING && !cantFetchMore)
if (!fetching){
fetching = YES;

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
[self fetchNews];
});


}

}

(我们的想法是,当我们到达 N-PADDLE_BEFORE_FETCHING 单元时,仅当我们仍然可以获取一些新闻时才开始获取其他新闻 - 见下文 - 并且当前尚未运行获取)

然后执行 fetchNews :

-(void)fetchNews{


[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

NSString *url = [NSString stringWithFormat:@"%@%@%@%@%d%@",HOSTNAME,GET_NEWS,[defaults objectForKey:@"oAuthToken"],@"&limit=",FETCH_SIZE_NEWS,[NSString stringWithFormat:@"&offset=%d",self.newsList.count]];

NSURLRequest *request =[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url]];


AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

#if DEVELOPMENT_MODE
NSLog(@"News : %@",JSON);
NSLog(@"Response : %@\n Request : %@",response,request);
#endif

//NSLog(@"Number of news fetched : %d",((NSArray*)JSON[@"data"]).count);

for (NSDictionary *d in JSON[@"data"]){
News *new = [[News alloc] initWithDictionary:d];
[self.newsList addObject:new];
new = nil;
}


if ((((NSArray*)JSON[@"data"]).count)%FETCH_SIZE_NEWS !=0) cantFetchMore = YES;
//NSLog(@"%d cantFetch",cantFetchMore);

[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

[self.tableView reloadData];

fetching = NO;

} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"Request error : %@ %@ %@",request,error, JSON);
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
fetching = NO;

}];


[operation start];

}

这将从服务器获取 FETCH_SIZE_NEWS 附加新闻,从正确的偏移量开始,该偏移量是 newsList 数组的当前大小。另外,如果获取的新闻计数 % FETCH_SIZE_NEWS 不等于 0,则意味着我们无法获取其他新闻(这将阻止在滚动 UITableView 时调用 Web 服务)。

我的问题是,当提取完成时(正是当我看到状态栏中运行的事件轮时),它会阻止 GUI,并且我无法继续从 n-PADDLE_BEFORE_FETCHING 单元格向下滚动到 n 单元格,甚至向上滚动到之前加载的单元格。

我真的不明白为什么 AFNetworking 应该异步运行。

有什么想法吗?

谢谢

最佳答案

完成 block 中的 for 循环正在主线程上运行,可能会导致速度变慢。尝试将该代码发送到另一个线程/队列。

关于ios - UITableView - AFNetworking 后台操作卡住滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18962184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com