iOS开发关于UITableView从网络中获取到数据源,却在UITableView中不显示的问题

本文介绍如何解决iOS开发中UITableView无法正确显示从网络获取的数据的问题。通过调整数据加载时机,确保数据更新后能立即反映在UITableView上。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

大神就不用看了,对你来说肯定没什么营养,只针对新手朋友!!!

相信在iOS开发中大家会经常的应用到UITableView控件,于此同时我们也少不了与网络打交道,那么问题就产生了:

为什么我从网络获取到了数据源,但是却在UITableView不能成功显示出来?

下面,我用一个例子来给大家展示

首先这是我自己定义的一个类


  1. #import "SecondViewController.h"


  2. @interface SecondViewController ()

  3. @property NSMutableData *mutableData;
  4. @property NSString *string;
  5. @property NSMutableArray *courses;

  6. @end

  7. @implementation SecondViewController

  8. - (void)viewDidLoad {
  9.     NSString *path = @"这是URL地址";
  10.     NSURL *url = [NSURL URLWithString:path];
  11.     NSURLRequest *request = [NSURLRequest requestWithURL:url];
  12.     NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
  13.     [connection start];
  14.     [super viewDidLoad];
  15.     self.classBarItem.badgeValue = nil;
  16.     
  17. }

  18. - (void)didReceiveMemoryWarning {
  19.     [super didReceiveMemoryWarning];
  20.     // Dispose of any resources that can be recreated.
  21. }

  22. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
  23.     NSLog(@"%@", response);
  24. }

  25. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
  26.     if(_mutableData == nil){
  27.         _mutableData = [[NSMutableData alloc]init];
  28.     }
  29.     [_mutableData appendData:data];
  30. }

  31. - (void)connectionDidFinishLoading:(NSURLConnection *)connection{
  32.     _string = [[NSString alloc]initWithBytes:[_mutableData bytes] length:[_mutableData length] encoding:NSUTF8StringEncoding];
  33.     NSJSONSerialization *json_courses = [NSJSONSerialization JSONObjectWithData:_mutableData options:0 error:nil];
  34.     NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:_mutableData options:0 error:nil];
  35.     _courses = [[NSMutableArray alloc] init];
  36.     for(int i = 0; i < [json count]; i++){
  37.         NSString *tag = @"course";
  38.         NSString *str_i = [[NSString alloc]initWithFormat:@"%i",i];
  39.         tag = [tag stringByAppendingString:str_i];
  40.         NSJSONSerialization *json_course = [json_courses valueForKey:tag];
  41.         NSString *name = [json_course valueForKey:@"courseName"];
  42.         NSLog(@"%@",name);
  43.         [_courses addObject:name];
  44.     }
  45.     NSLog(@"%@",_courses);
  46.     //获取NSMuTableArray中第n个元素的值
  47.     //NSLog(@"%@", [_courses objectAtIndex:1]);
  48.     _mutableData = nil;
  49. }

  50. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  51.     return 1;
  52. }

  53. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  54.     NSLog(@"Array count is %i",[_courses count]);
  55.     return [_courses count];
  56. }


  57.  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  58.      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"courses" forIndexPath:indexPath];
  59.      cell.textLabel.text = [_courses objectAtIndex:[indexPath row]];
  60.  // Configure the cell...
  61.  
  62.      return cell;
  63.  }
  64.  

  65. /*
  66.  // Override to support conditional editing of the table view.
  67.  - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
  68.  // Return NO if you do not want the specified item to be editable.
  69.  return YES;
  70.  }
  71.  */

  72. /*
  73.  // Override to support editing the table view.
  74.  - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
  75.  if (editingStyle == UITableViewCellEditingStyleDelete) {
  76.  // Delete the row from the data source
  77.  [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
  78.  } else if (editingStyle == UITableViewCellEditingStyleInsert) {
  79.  // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
  80.  }
  81.  }
  82.  */

  83. /*
  84.  // Override to support rearranging the table view.
  85.  - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
  86.  }
  87.  */

  88. /*
  89.  // Override to support conditional rearranging of the table view.
  90.  - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
  91.  // Return NO if you do not want the item to be re-orderable.
  92.  return YES;
  93.  }
  94.  */

  95. /*
  96.  #pragma mark - Navigation
  97.  
  98.  // In a storyboard-based application, you will often want to do a little preparation before navigation
  99.  - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  100.  // Get the new view controller using [segue destinationViewController].
  101.  // Pass the selected object to the new view controller.
  102.  }
  103.  */

  104. @end


程序成功获取到了数据源:


但是,问题就出现了,大家注意到没有,我用来存放网络读取的数据的NSMutableArray的count值为0,但是我也成功获取到了网络数据。

首先,分析,程序先执行输出了盛放我所需数据的长段,然后才从网络获取数据,那么我们就可以推断出,程序必然是先创建了UITableView,之后才获取到了网络数据。

问题产生的原因:程序在获取网络资源时并不会在主线程当中进行,所以程序会先执行之后的代码,然后再来获取网络资源

那么解决这个问题的方法也就明了了,在获取到网络资源后我们需要把它重新加载到tableView上

此时我们只需要在connectionDidFinishLoading末尾添加[self.tableView reloadData];即可

OK,大功告成!

运行结果如下:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值