如何在NSUserDefaults中存储多个NSMutableDictionarys

时间:2022-07-21 21:17:35

I am trying to store multiple NSMutableDictionarys in NSUserDefaults I have tried this:

我试图在NSUserDefaults中存储多个NSMutableDictionarys我试过这个:

-(void)storeNotification:(NSDictionary*)dict{
    NSMutableDictionary *dic = [dict mutableCopy];
    //add read object to dic
    [dic setObject:@"NO" forKey:@"read"];

    //get stored arrayofdics
    NSMutableArray *arrayofdics = [[NSUserDefaults standardUserDefaults] objectForKey:@"arrayofdics"];
    if([arrayofdics count] == 0){
        arrayofdics = [[NSMutableArray alloc] init];
    }

    //add dic to arrayofdics
    [arrayofdics addObject:dic];

    //store arrayofdics
    [[NSUserDefaults standardUserDefaults] setObject:arrayofdics forKey:@"arrayofdics"];
    NSLog(@"stored: %@", arrayofdics);
}

So that I can then modify the read key in a dic like this:

这样我就可以在这样的dic中修改读取键:

-(void)markAsRead:(int)dic_index{
    NSMutableArray *arrayofdics = [[NSUserDefaults standardUserDefaults] objectForKey:@"arrayofdics"];
    NSMutableDictionary *dic = [arrayofdics objectAtIndex:dic_index];
    [dic setObject:@"YES" forKey:@"read"];
    [arrayofdics replaceObjectAtIndex:dic_index withObject:dic];
    [[NSUserDefaults standardUserDefaults] setObject:arrayofdics forKey:@"arrayofdics"];
}

and also am able to iterate all of the storeNotifications

并且还能够迭代所有storeNotifications


The log is showing:

日志显示:

stored: ( { read = NO; ... })

存储:({read = NO; ...})

but when storeNotification is called the second time I get an error:

但是第二次调用storeNotification时出现错误:

Printing description of arrayofdics->isa:
(Class) isa = __NSCFArray
(lldb) 

如何在NSUserDefaults中存储多个NSMutableDictionarys

Which means the array is not being stored properly. Any ideas why? Or ways to do this better?

这意味着阵列未正确存储。有什么想法吗?或者更好地做到这一点的方法?

1 个解决方案

#1


1  

This error is due to calling mutable functions in immutable objects

此错误是由于在不可变对象中调用可变函数

Userdefaults always return a immutable objects. so make mutable when u get objects from userdefaults.

Userdefaults始终返回不可变对象。所以当你从userdefaults获取对象时,make变量。

 NSMutableArray *arrayofdics = [[[NSUserDefaults standardUserDefaults] objectForKey:@"arrayofdics"] mutableCopy];

#1


1  

This error is due to calling mutable functions in immutable objects

此错误是由于在不可变对象中调用可变函数

Userdefaults always return a immutable objects. so make mutable when u get objects from userdefaults.

Userdefaults始终返回不可变对象。所以当你从userdefaults获取对象时,make变量。

 NSMutableArray *arrayofdics = [[[NSUserDefaults standardUserDefaults] objectForKey:@"arrayofdics"] mutableCopy];