gpt4 book ai didi

objective-c - 在我滚动之前,数据不会加载到 UITableView 中

转载 作者:IT老高 更新时间:2023-10-28 11:33:06 29 4
gpt4 key购买 nike

我正在尝试在单元格中加载解析的数据,但问题是它是同步发生的,并且 UitableView 在数据加载完成之前不会显示。我试图通过使用 performSelectorInBackground 来解决这个问题,但现在数据不会加载到单元格中,直到我开始滚动。这是我的代码:

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

[self performSelectorInBackground:@selector(fethchData) withObject:nil];


}


- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
self.listData = nil;
self.plot=nil;
}


-(void) fethchData

{
NSError *error = nil;
NSURL *url=[[NSURL alloc] initWithString:@"http://www.website.com/"];
NSString *strin=[[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];

HTMLParser *parser = [[HTMLParser alloc] initWithString:strin error:&error];

if (error) {
NSLog(@"Error: %@", error);
return;
}

listData =[[NSMutableArray alloc] init];
plot=[[NSMutableArray alloc] init];

HTMLNode *bodyNode = [parser body];
NSArray *contentNodes = [bodyNode findChildTags:@"p"];


for (HTMLNode *inputNode in contentNodes) {
[plot addObject:[[inputNode allContents] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
}


NSArray *divNodes = [bodyNode findChildTags:@"h2"];

for (HTMLNode *inputNode in divNodes) {

[listData addObject:[[inputNode allContents] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];

}
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

static NSString *CellIdentifier = @"Cell";
//here you check for PreCreated cell.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

}

//Fill the cells...


cell.textLabel.text = [listData objectAtIndex:indexPath.row];
cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
cell.textLabel.numberOfLines=6;
cell.textLabel.textColor=[UIColor colorWithHue:0.7 saturation:1 brightness:0.4 alpha:1];


cell.detailTextLabel.text=[plot objectAtIndex:indexPath.row];
cell.detailTextLabel.font=[UIFont systemFontOfSize:11];
cell.detailTextLabel.numberOfLines=6;

return cell;


}

最佳答案

把这个放在数据加载成功后:

dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});

这解决了在您不在主线程中时调用 GUI 更新的问题。

此代码使用 Apple 的 GCD 技术强制重新加载数据函数在主线程上运行。阅读更多关于 Concurrency Programming Guide为了更多的理解(这是一个很大的领域,所以很难在评论中解释)无论如何,如果不是很了解,不很推荐,因为它会导致程序在一些罕见的情况下崩溃。

关于objective-c - 在我滚动之前,数据不会加载到 UITableView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10885268/

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