Iphone 字典中的更新键

Iphone 字典中的更新键,iphone,objective-c,cocoa-touch,Iphone,Objective C,Cocoa Touch,我在NSArray里有几本词典。我想修改其中一个字典中的BOOL,这样整个数组都会有这种变化(它加载一个tableview) 我有这个密码,但它不会改变密码。我觉得我需要删除mutableCopy才能工作,但是它崩溃了 NSLog(@"before: %@", self.currentScopeArray); if (cell.accessoryType == UITableViewCellAccessoryNone) { cell.accessoryType =

我在NSArray里有几本词典。我想修改其中一个字典中的BOOL,这样整个数组都会有这种变化(它加载一个tableview)

我有这个密码,但它不会改变密码。我觉得我需要删除
mutableCopy
才能工作,但是它崩溃了

    NSLog(@"before: %@", self.currentScopeArray);
    if (cell.accessoryType == UITableViewCellAccessoryNone) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        [[self.currentScopeArray objectAtIndex:iIndexPath.row] setObject:[NSNumber numberWithBool:YES] forKey:@"enabledByDefault"];
    } else {    
        if (!(self.currentScopeArray.count < 2)) {
            cell.accessoryType = UITableViewCellAccessoryNone;
            [[[self.currentScopeArray objectAtIndex:iIndexPath.row]mutableCopy] setObject:[NSNumber numberWithBool:NO] forKey:@"enabledByDefault"];
        }
    }
    NSLog(@"after: %@", self.currentScopeArray);
NSLog(@“before:%@”,self.currentScopeArray);
if(cell.accessoryType==UITableViewCellAccessoryNone){
cell.accessoryType=UITableViewCellAccessoryCheckmark;
[[self.currentScopeArray objectAtIndex:iIndexPath.row]setObject:[NSNumber numberWithBool:YES]forKey:@“enabledByDefault”];
}否则{
如果(!(self.currentScopeArray.count<2)){
cell.accessoryType=UITableViewCellAccessoryNone;
[[[self.currentScopeArray objectAtIndex:iIndexPath.row]mutableCopy]setObject:[NSNumber numberWithBool:NO]forKey:@“enabledByDefault”];
}
}
NSLog(@“之后:%@”,self.currentScopeArray);

如果你创建了一个对象的可变副本,那么它就是一个副本。如果要对已在
currentScopeArray
中的对象进行变异,则需要在数组中已有可变对象,或者需要获取可变副本,对其进行变异,然后替换原始对象

我建议前者诚实一点。因此,您可以通过添加
NSMutableDictionary
s来创建
currentScopeArray
,然后只需替换此行:

[[[self.currentScopeArray objectAtIndex:iIndexPath.row]mutableCopy] setObject:[NSNumber numberWithBool:NO] forKey:@"enabledByDefault"];
为此:

[[self.currentScopeArray objectAtIndex:iIndexPath.row] setObject:[NSNumber numberWithBool:NO] forKey:@"enabledByDefault"];

您正在向NSArray添加一组NSDictionary。我建议你

  • 将NSArray设置为NSMutableArray
  • 将NSDictionary转换为NSMutableDictionary
为什么??因为您已经需要修改字典中的值。而且,您可能还希望从数组中添加/删除字典。一旦您使它们可变,您就可以执行以下操作:

   [[self.currentScopeArray objectAtIndex:iIndexPath.row] setObject:[NSNumber numberWithBool:YES] forKey:@"enabledByDefault"];


当前实现的另一个问题是,您操作的是可变副本,而不是原始字典。副本已修改,而原件未修改

因此,您从该行中删除了
mutableCopy
,但我还需要做什么?如果我只是这么做的话,应用程序就会崩溃。你需要该数组中的字典是
NSMutableDictionary
s。首先,您是如何创建阵列的?
[[self.currentScopeArray objectAtIndex:iIndexPath.row] setObject:[NSNumber numberWithBool:NO] forKey:@"enabledByDefault"];