1

我最近完成了名为 Bird Watching 的关于表视图的苹果教程,并且效果很好。但是,我现在正试图通过添加一个编辑按钮来进一步处理它,并且似乎遇到了问题。

下面是 MasterViewController 用来创建我的表的代码。这工作正常。

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

static NSDateFormatter *formatter = nil;
if(formatter == nil){
    formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

BirdSighting *sightingAtIndex = [self.dataController objectInListAtIndex:indexPath.row];
[[cell textLabel]setText:sightingAtIndex.name];
[[cell detailTextLabel]setText:[formatter stringFromDate:(NSDate *)sightingAtIndex.date]];
return cell;
}

我已经尝试使用其中的一些代码来使编辑按钮正常工作,下面是我创建的。这不起作用,我不知道如何解决它。

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{


if (editingStyle == UITableViewCellEditingStyleDelete) {
    BirdSighting *sightingAtIndex = [self.dataController removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}

我收到的错误消息之一是“BirdSightingDataController 没有可见的@interface 声明选择器 removeObjectAtIndex。

4

1 回答 1

2

我在 Apple 网站上查找了Bird Watching教程,以准确了解您在说什么以及这些对象是哪些类的实例。

在您的tableView:commitEditingStyle:forRowAtIndexPath:方法中,您尝试删除某个对象。删除对象时,您必须确保从视图(在本例中为表视图)和模型对象(在本例中为数据控制器)中删除它。您从表格视图中删除了该行,如下所示:

[tableView deleteRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationFade];

这部分看起来不错。但是,您尝试使用以下代码行从数据控制器中删除对象:

BirdSighting *sightingAtIndex = [self.dataController removeObjectAtIndex:indexPath.row];

您将removeObjectAtIndex:方法发送到self.dataController. 该removeObjectAtIndex:方法只能发送到NSMutableArray. 您的数据控制器是 的实例BirdSightingDataController,而不是NSMutableArray. 因此,在尝试将removeObjectAtIndex:方法发送到之后self.dataController,您会遇到错误。

要访问数据控制器数组的某个索引处的对象,您声明并实现了如下objectInListAtIndex:方法:

- (BirdSighting *)objectInListAtIndex:(NSUInteger)theIndex {
    return [self.masterBirdSightingList objectAtIndex:theIndex];
}

现在您想删除数据控制器数组的某个索引处的对象,您也可以removeObjectInListAtIndex:BirdSightingDataController头文件中声明一个方法。然后,您可以像这样实现它:

- (void)removeObjectInListAtIndex:(NSUInteger)theIndex {
    [self.masterBirdSightingList removeObjectAtIndex:theIndex];
}

请注意,此方法不返回任何内容,因为它只是从数组中删除一个对象。确保在头文件和实现文件中都使用- (void)而不是。- (BirdSighting *)

现在,removeObjectAtIndex:您可以简单地从数据控制器中删除对象(用户删除),而不是将方法发送到您的数据控制器,如下所示:

[self.dataController removeObjectInListAtIndex:indexPath.row];
于 2012-10-20T00:25:53.683 回答