ios - 使用 NSMutableArray 将变异方法发送到不可变对象(immutable对象)

标签 ios objective-c nsmutablearray nsuserdefaults

我发现了错误 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object”当我第二次将对象添加到可变数组时,第一次成功添加但第二次崩溃了应用程序,我认为当我将对象添加到数组时存在问题。
下面的代码是崩溃。

- (void) viewWillAppear:(BOOL)animated
{

    if ([defaults objectForKey:@"Groups"] != nil)
    {
        NSLog(@"not nil defaults.");
        arrGroups = (NSMutableArray *)[defaults objectForKey:@"Groups"];
    }
    else
    {
        NSLog(@"nil defaults.");
        arrGroups = [[NSMutableArray alloc] init];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

{

NSLog(@"button index == %ld",(long)buttonIndex);
//txtCategory = [[alertView textFieldAtIndex:0] text];

if (buttonIndex == 1)
{
    //[self addingCategory:self];
    NSLog(@"Adding Group name = %@",[[alertView textFieldAtIndex:0]text]);
    [arrGroups addObject:[[alertView textFieldAtIndex:0]text]]; **//Crash here! at the time of add second object or also when i remove first object**
    NSLog(@"Added to array.");
    [defaults setObject:arrGroups forKey:@"Groups"];
    [defaults synchronize];
    //[defaults release];
    [tblGroups reloadData];
}

}

当我当时删除第一个对象时,我将 userdefault 替换为更新的数组,所以我认为没有问题。我没有找到导致崩溃的适当原因。

所以请支持我理解我的问题或解决方案,但不理解问题我无法理解解决方案,所以请任何人告诉我为什么会发生这种情况。

谢谢。

最佳答案

分配给 NSMutableArray 的问题是,它只有在 defaultDefects 为给定键分配了 NSMutableArray 时才有效。

注意:NSUserDefaults 总是返回一个不可变对象(immutable对象)。

改为这样做

NSMutableArray *arrGroups = [[defaults objectForKey:@"Groups"]mutableCopy];

这保证了可变副本。

另一种方式是。
arrGroups = [[NSMutableArray alloc]initWithArray:[defaults objectForKey:@"Groups"]]; //in your viewWillAppear where you assign array from defaults.

关于ios - 使用 NSMutableArray 将变异方法发送到不可变对象(immutable对象),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29092365/

相关文章:

ios - 在 View 外部创建的 UIButton 不起作用

ios - 如何有效地将 SKS 中的子节点与场景中的代码链接起来

ios - 如何追加数组。或者我如何将模型转换为 nsmuttable 数组

objective-c - 注册全局热键而不支持启用辅助设备

objective-c - CAKeyframeAnimation 关键路径错误

cocoa - NSMutableArray - 数组弹出等效项

ios - 在 Parse 数据库中查询具有多个指针的类

ios - 如何对包含带有字符和小数的对象的数组进行排序?

iphone - 如何存储多个坐标和 map 套件绘图路线

ios - 如何从 Objective C 中的另一个值替换 NSDictionary 值?