数据不会从 JSON 解析加载到某些 Tableview 单元格上
Posted
技术标签:
【中文标题】数据不会从 JSON 解析加载到某些 Tableview 单元格上【英文标题】:Data dosen't load on some Tableview cell from JSON parse 【发布时间】:2016-01-18 06:13:33 【问题描述】:我在 XCODE 7.1 上制作了简单的应用程序。 我只在 tableview 单元格中显示 2 个标签和 1 个图像。我正在解析来自这个 URL 的数据。我只是在 Tableview 中加载数据这里我把 ViewController.m 文件的代码
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
[super viewDidLoad];
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
activityIndicator.alpha = 1.0;
[self.view addSubview:activityIndicator];
activityIndicator.center = CGPointMake([[UIScreen mainScreen]bounds].size.width/2, [[UIScreen mainScreen]bounds].size.height/2);
[activityIndicator startAnimating];//to start animating
// Do any additional setup after loading the view, typically from a nib.
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://www.androidbegin.com/tutorial/jsonparsetutorial.txt"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error)
if (error)
NSLog(@"Error: %@", error);
else
[activityIndicator stopAnimating];
_responsedic = (NSDictionary*) responseObject;
_Worldpopulation = [_responsedic valueForKey:@"worldpopulation"];
_imageURL = [_Worldpopulation valueForKey:@"flag"];
_country = [_Worldpopulation valueForKey:@"country"];
_population = [_Worldpopulation valueForKey:@"population"];
NSLog(@"Data:%@",_imageURL);
NSLog(@"Population",_population);
NSLog(@"Country",_country);
// NSLog(@"%@",_MovieList);
//NSLog(@"Array: %@",_imageURL);
//NSLog(@"%@",responseObject);
];
[dataTask resume];
- (void)didReceiveMemoryWarning
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
return 10;
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
NSString *Identifier = @"mycell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:Identifier];
// Set and load the images
[cell.imageView sd_setImageWithURL:[_imageURL objectAtIndex:indexPath.row] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL)
// Get rid of the activity indicator when the image has been loaded
];
cell.textLabel.text = [_country objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [_population objectAtIndex:indexPath.row];
return cell;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//NSString *rowValue = self.friends[indexPath.row+1];
NSString *message = [[NSString alloc] initWithFormat:@"You selected %@",[_country objectAtIndex:indexPath.row]];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"YOU SELECT"
message:message
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
我正在使用AFNetworking
3.0 和SDWebImage
进行图像加载。数据解析成功并显示在tableview 中。我在下面附上了屏幕截图
问题是所有数据都没有显示在 tableview 单元格中我还在成功加载但未显示在单元格中的 tableview 数据的每个单元格上放置了警报对话框。我到处搜索我找不到解决方案我正在使用 3G 连接所以网速不是问题请有人帮忙。
【问题讨论】:
您在单元格的非常不稳定的状态下开始异步操作,此外,出列单元格使其变得更加复杂。我之前在使用 SDWebImage 时遇到过这样的问题,我不得不在UITableViewCell
的子类中移动加载图像(仍然使用 SDWebImage)以更好地处理 prepareForReuse
的情况等等。您需要取消以前的操作,以防您的单元格出队...
是的,但我如何从 UITableView 的 单元格子类加载图像。
【参考方案1】:
尝试使用完成块中的更新数据重新加载表视图。
NSURL *URL = [NSURL URLWithString:@"http://www.androidbegin.com/tutorial/jsonparsetutorial.txt"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error)
if (error)
NSLog(@"Error: %@", error);
else
[activityIndicator stopAnimating];
_responsedic = (NSDictionary*) responseObject;
_Worldpopulation = [_responsedic valueForKey:@"worldpopulation"];
_imageURL = [_Worldpopulation valueForKey:@"flag"];
_country = [_Worldpopulation valueForKey:@"country"];
_population = [_Worldpopulation valueForKey:@"population"];
NSLog(@"Data:%@",_imageURL);
NSLog(@"Population",_population);
NSLog(@"Country",_country);
// NSLog(@"%@",_MovieList);
//NSLog(@"Array: %@",_imageURL);
//NSLog(@"%@",responseObject);
//Added Code -> Reloading data on Main queue for update
dispatch_async(dispatch_get_main_queue(), ^
[self.tableview reloadData];
);
];
[dataTask resume];
希望对您有所帮助。 谢谢。
【讨论】:
【参考方案2】:1)解析数据并获取数据后重新加载表
-(void)ParseData
NSURLSession * session = [NSURLSession sharedSession];
NSURL * url = [NSURL URLWithString: @"http://www.androidbegin.com/tutorial/jsonparsetutorial.txt"];
//Create URLReques
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
// Set Method POST/GET
[request setHTTPMethod:@"GET"];
// Asynchronously Api is hit here
NSURLSessionDataTask* dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
if (!error) //If error nil
//Serialization data
NSDictionary * json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"json %@",json);
array=[json valueForKey:@"worldpopulation"];
dispatch_async(dispatch_get_main_queue(), ^(void)
if(array.count!=0)
//Reload table View
[_tblView reloadData];
);
else
//failure;
];
[dataTask resume] ; // Executed task
2) Table View DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
if(array.count!=0)
return [array count];
return 0;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell;
//= [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.backgroundColor =[UIColor whiteColor];
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
UILabel *lblCountry=(UILabel*)[cell viewWithTag:2];
lblCountry.text= [[array objectAtIndex:indexPath.row]valueForKey:@"country"];
UILabel *lblPopulation=(UILabel*)[cell viewWithTag:3];
lblPopulation.text= [[array objectAtIndex:indexPath.row]valueForKey:@"population"];
UIImageView *img = (UIImageView *)[cell viewWithTag:1];
[img setImageWithURL:[NSURL URLWithString:[[array objectAtIndex:indexPath.row]valueForKey:@"flag"]]];
return cell;
【讨论】:
以上是关于数据不会从 JSON 解析加载到某些 Tableview 单元格上的主要内容,如果未能解决你的问题,请参考以下文章