【问题标题】:Why isn't my tableView loading?为什么我的 tableView 没有加载?
【发布时间】:2012-01-09 09:40:28
【问题描述】:

我有以下代码,我相信NSFetchRequest 实际上是在工作,但在viewWillAppear 运行后,我的 tableView(peopleList) 中没有任何显示。

-(void)viewWillAppear:(BOOL)animated{

  AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
  NSManagedObjectContext *moc = [appDelegate managedObjectContext]; 

  NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Person" 
                                                     inManagedObjectContext:moc];

  NSFetchRequest *request = [[NSFetchRequest alloc] init];
  [request setEntity:entityDescription];


  NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES];
  [request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];


  NSError *error = nil;

  NSLog(@"Count for request is %a", [moc countForFetchRequest:request error:&error]);

  personArray = [moc executeFetchRequest:request error:&error];

  [peopleList reloadData];
}

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

  static NSString *cellIdentifier = @"Cell";

  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
  if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier];
  }

  NSString *cellValue = [personArray objectAtIndex:indexPath.row];
  cell.textLabel.text = cellValue;

  return cell;

}

以防万一,我的情节提要如图所示。

我的控制台显示“请求计数为 23”,这让我认为故障在于让数组本身显示在界面中。需要做什么才能让我的 personArray 出现在 peopleList 中?

感谢任何帮助。

【问题讨论】:

    标签: iphone ios tableview xcode4.2 storyboard


    【解决方案1】:

    您需要声明一个 UITableViewDataSource,它是一个实现该协议并向您的表提供数据的对象。这是调用 cellForRowAtIndexPath 的部分。它经常是自我,即tableViewController 类,因为它通常将数组作为局部变量。

    myTableView.dataSource = self;
    

    在你的头文件中,做这样的事情:

     @interface myTableViewController : UITableViewController <UITableViewDelegate,UITableViewDataSource> {
    
     }
    

    【讨论】:

    • 我得到一个'将'MainScreen *const_strong'传递给不兼容类型'id'的参数错误。
    • 您的表视图控制器是否声明它实现了 UITableViewDataSource 协议?查看我的上一次编辑。
    • 不,不是,但我已经更正了。现在它抛出一个异常,并声明行“cell.textLabel.text = cellValue;”是问题所在。控制台显示 'NSInvalidArgumentException',原因:'-[Person isEqualToString:]: unrecognized selector sent to instance 0x912f2c0'。
    • 您的 personArray 中有哪些类型的对象?它们是 NSString 实例还是某种 Person 类?如果是 Person 类,则需要执行 Person.lastName 之类的操作。
    • 这是一个 Person 类,有两个属性 firstName 和 lastName。
    【解决方案2】:

    如果你 fetch 工作正常,那么我猜你还没有为 tableview 设置数据源和/或委托。

    【讨论】:

      猜你喜欢
      • 2015-12-24
      • 1970-01-01
      • 2016-09-16
      • 1970-01-01
      • 1970-01-01
      • 2011-11-15
      • 2013-06-16
      • 2018-08-15
      • 2013-02-28
      相关资源
      最近更新 更多