iOS开发笔记 NSUserDefaults 存储可变数组问题

不多废话,我在项目里遇到了这么一个问题:把数据存到一个可变数组里,然后用NSUserDefaults 存到沙盒中;在存入数据时主线程卡住,但是不崩溃,也不知道为什么

NSMutableArray *infoArr = [[NSUserDefaults standardUserDefaults] mutableArrayValueForKey:@"infoArr"];//取出数组

[infoArr addObject: cardInfoDic]; //往数组中添加数据

[[NSUserDefaultsstandardUserDefaults] setObject:infoArr forKey:@"infoArr"];  

[[NSUserDefaultsstandardUserDefaults]synchronize];

这是我的代码,多次调试后发现是在这段代码卡住了

[[NSUserDefaultsstandardUserDefaults] setObject:infoArr forKey:@"infoArr"];

经过多次尝试后发现无法解决,最后在stackoverflow上找到了答案....

When you store mutable objects to NSUserDefaults, it stores an immutable copy of it so you can't change it directly like that. You have to get the mutable copy out of defaults, change it, and then set it back, replacing old object in defaults.

其实我不认识英文,都是我编的

当你使用NSUserDefaults存储可变对象,它存储的是一个不可变的副本,你无法像这样直接改变它。你必须把数组可变复制出来,再修改它,最后把它存回来,更换旧对象。


NSMutableArray*infoArr = [[NSUserDefaults standardUserDefaults] mutableArrayValueForKey: @"infoArr"];

NSMutableArray *mutableCopyArr = [infoArr mutableCopy];

[mutableCopy ArraddObject: cardInfoDic];

[[NSUserDefaults standardUserDefaults] setObject: mutableCopyArrforKey:@"infoArr"];

[[NSUserDefaults standardUserDefaults] synchronize];


这是修改后的代码

你可能感兴趣的:(iOS开发笔记 NSUserDefaults 存储可变数组问题)