通过 UITableView 从 NSMutableDictionary 添加/删除项目

Posted

技术标签:

【中文标题】通过 UITableView 从 NSMutableDictionary 添加/删除项目【英文标题】:Add / Delete Item from NSMutableDictionary through UITableView 【发布时间】: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 移出)。'"

有人可以帮我吗?

【问题讨论】:

【参考方案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 ,现在它抛出一个错误,说它不正确。仍然得到关于总数的相同错误。有什么建议吗?

以上是关于通过 UITableView 从 NSMutableDictionary 添加/删除项目的主要内容,如果未能解决你的问题,请参考以下文章

通过 UITableView 从 NSMutableArray 中删除项目

如何通过滑动从 Parse 中的 UITableView 中删除对象?

如何从通过情节提要创建的 UITableView 中提取 UIView?

-[__NSDictionaryI rangeOfString:options:]: 无法识别的选择器发送到实例

使用 NSFetchedResultsController 从 UITableView 中删除

从 NSDate 获取 UITableView 标题