objective-c - 如何将多个 NSMutableDictionaries 中的键更改为当前值的 -1?

标签 objective-c ios cocoa-touch uitableview

我有一个 UITableView,其数据源是 NSMutableArray。该数组包含带有“name”、“index”、“color”和“string”键的 NSMutableDictionaries。索引键代表对象所在的 TableView 中的行。移动和添加对象可以很好地使用它并保持它们正确和更新,但是当我尝试删除对象时,删除后对象的“索引”键行 1 折。我尝试过很多事情,但每一次尝试都失败了。有人可以给我一些现场吗?这是数组的代码:

contentarray = [[NSArray arrayWithObjects:
    [NSMutableDictionary dictionaryWithObjectsAndKeys:
        @"Object 1", @"name",
        @"0", @"index",
        @"0", @"color",
        @"Example", @"string",
        nil],
    [NSMutableDictionary dictionaryWithObjectsAndKeys:
        @"Object 2", @"name",
        @"1", @"index",
        @"1", @"color",
        @"String 2", @"string",
        nil],
    [NSMutableDictionary dictionaryWithObjectsAndKeys:
        @"Object 3", @"name",
        @"2", @"index",
        @"0", @"color",
        @"String 3", @"string",
        nil],
    [NSMutableDictionary dictionaryWithObjectsAndKeys:
        @"Object 4", @"name",
        @"3", @"index",
        @"2", @"color",
        @"String 4", @"string",
        nil],
    [NSMutableDictionary dictionaryWithObjectsAndKeys:
        @"Object 5", @"name",
        @"4", @"index",
        @"0", @"color",
        @"String 5", @"string",
        nil],
    nil] mutableCopy];

最佳答案

将此问题更多地视为练习(通常不会在数组元素中存储索引,没有必要)我将提供该问题的解决方案...

首先,您可能应该使用 NSNumber 对象来表示 NSDictionary 中的数字,因此您的数组充满了像这样的字典

[NSMutableDictionary dictionaryWithObjectsAndKeys:
    @"Object 1", @"name",
    [NSNumber numberWithInt:0], @"index",
    [NSNumber numberWithInt:0], @"color",
    @"Example", @"string",
    nil],

此外,我认为使用字典作为数据类型是相当糟糕的形式,你最好创建一个类来表示你在这里存储的任何内容......但是,对于你的解决方案问题...

修改数组后,您需要迭代该数组,将索引更新为正确的值。像下面这样的函数就足够了:

- (void)correctContentArrayIndices {
    int contentArrayIndex = 0;
    for(NSMutableDictionary *dict in contentarray) {
        NSString *stringRepresentationOfIndex = [NSString stringWithFormat:@"%i", 
                                                 contentArrayIndex];
        [dict setObject:stringRepresentationOfIndex forKey:@"index"];
        contentArrayIndex++;
    }
}

关于objective-c - 如何将多个 NSMutableDictionaries 中的键更改为当前值的 -1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7896421/

相关文章:

ios - 如何从 NSDate 获得 1 小时的 future 时差

iphone - 最佳实践 - 访问全局偏好

ios - 当颜色来自 NSArray 时,如何在 tableViewCell 中设置多个 UIView 的边框颜色

ios - 如何防止隐藏相册显示在 CTAssetsPickerController 上

objective-c - 在 Objective-C 和 Linux 上进行游戏编程

ios - UIPickerView NSInvalidArgumentException',原因: '-[__NSCFString superview]: unrecognized selector sent to instance

ios - 使 UIScrollView 中的顶部图像在 ScrollView 边界上放大?

ios - Swift 内容标签?

objective-c - 适用于 iPhone/iPad 的线性回归库或代码片段?

iphone - 如何通过UINavigationController设置一个navigationController?