【问题标题】:Add / Delete Item from NSMutableDictionary through UITableView通过 UITableView 从 NSMutableDictionary 添加/删除项目
【发布时间】:2012-05-20 04:11:37
【问题描述】:

我有一个带有 NSMutableDictionary 的 .plist 文件,我正在像这样填充 UITableView:

- (void)viewDidLoad
{
[super viewDidLoad];

NSString *myFile = [[NSBundle mainBundle]
                    pathForResource:@"courses" ofType:@"plist"];
courses = [[NSMutableDictionary alloc] initWithContentsOfFile:myFile];
courseKeys = [courses allKeys];

}

还有:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:    (NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Course";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

// Configure the cell...

NSString *currentCourseName = [courseKeys objectAtIndex:[indexPath row]];
[[cell textLabel] setText:currentCourseName];

return cell;
}

我正在尝试允许用户滑动 + 删除并使用 UiTableView 单元将新项目“添加”到 plist。这是我用来执行此操作的代码:

- (void)tableView:(UITableView *)tableView commitEditingStyle:  (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Delete the row from the data source
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject: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

当我运行模拟器并执行此操作时,它给了我一个错误,说明

“无效更新:第0节中的行数无效。更新后现有节中包含的行数(7)必须等于更新前该节中包含的行数(7),加上或减去从该节插入或删除的行数(0 插入,1 删除)并加上或减去移入或移出该节的行数(0 移入,0 移出)。'"

有人可以帮我吗?

【问题讨论】:

    标签: objective-c ios xcode cocoa-touch


    【解决方案1】:

    您正在从 courseKeys 数组中填充您的表格。所以在你的委托方法中

    - (void)tableView:(UITableView *)tableView commitEditingStyle:  (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
     {
         //whether it is an add or edit or delete modify your array from which you are populating the table and reload the table
     }
    

    【讨论】:

      【解决方案2】:

      您正在从表中删除该行,而不是从您的数据源中。 CourseKeys 需要是一个 mutableArray,您可以从中删除已删除的键。

      【讨论】:

      • 感谢您。我很难弄清楚如何做到这一点 - 我将数组更改为 nsmutablearray ,现在它抛出一个错误,说它不正确。仍然得到关于总数的相同错误。有什么建议吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-05
      • 2015-06-30
      • 2021-10-03
      • 2011-07-09
      相关资源
      最近更新 更多