【问题标题】:xcode core data section errorxcode核心数据部分错误
【发布时间】:2012-10-07 15:23:33
【问题描述】:

我有一个从核心数据中获取数据的表。我添加了一个部分,其中必须只有一个静态单元格。但我得到一个错误,我不知道为什么。

* 由于未捕获的异常 'NSRangeException' 导致应用程序终止,原因:'* -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'

探索和探索

- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self setupFetchedResultsController];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

if (section == 0) {

    return [[self.fetchedResultsController fetchedObjects] count];

} else if (section == 1) {

    return 1;

}

return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Category Cell";

CategoryCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[CategoryCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

// Configure the cell...

if (indexPath.section == 0) {

    NSLog(@"section %i",indexPath.section);

    Category *category = [self.fetchedResultsController objectAtIndexPath:indexPath];


    cell.categoryNameLabel.text = category.name;
    cell.categoryNumberItemsLabel.text = [NSString stringWithFormat:@"%i",category.containItem.count];

} else {
    //Static cell
}
return cell;
}

【问题讨论】:

  • 添加一个异常断点,这会告诉你你的代码崩溃的那一行。
  • 以编程方式,我认为没有错误。我是第一次使用故事板,可能有问题。
  • 你确定这个 [self.fetchedResultsController objectAtIndexPath:indexPath];做得对吗?
  • 我想是的,如果我设置一个部分,它会很好用

标签: objective-c xcode uitableview core-data


【解决方案1】:

您的两个 tableView 数据源方法不一致。

在numberOfRowsInSection 中,您返回获取结果控制器fetchedObjects 的总数。

在cellForRow... 中,您正在使用获取结果控制器的objectAtIndexPath 方法。

您应该根据文档获取部分信息对象并从那里获取行数:

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
    id <NSFetchedResultsSectionInfo> sectionInfo = [[<#Fetched results controller#> sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];
}

【讨论】:

  • 谢谢,错误就在这里,我没有实现这个方法 - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { return @""; }
猜你喜欢
  • 2014-07-05
  • 2015-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-20
  • 1970-01-01
  • 2013-01-30
相关资源
最近更新 更多