存储在 NSUserDefaults 中的 NSMutableArray 不会保存数据
当用户通过我的 iPhone 应用程序登录时,我会在 NSUserDefaults 中创建一堆默认元素。其中之一是 NSMutableArray,我通过以下方式添加它:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSMutableArray *theArray = [NSMutableArray array];
[prefs setObject:theArray forKey:@"theArray"];
这可以完美地工作。但是,当我想从 theArray
插入或检索值时,出现了问题。这是我的应用程序中另一个文件的摘录:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[[prefs objectForKey:@"theArray"] setValue:@"This is a value" forKey:@"aValue"];
NSLog(@"%@", [[prefs objectForKey:@"theArray"] valueForKey:@"aValue"]);
我希望在代码运行时在控制台中看到“这是一个值”,但我得到的是:
2011-08-08 18:35:17.503 MyApp[7993:10d03] (
)
数组怎么是空的?我使用 NSArray 尝试了同样的操作,得到了相同的结果。
When a user signs in through my iPhone app, I create a bunch of default elements in the NSUserDefaults. One of these is an NSMutableArray that I add the following way:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSMutableArray *theArray = [NSMutableArray array];
[prefs setObject:theArray forKey:@"theArray"];
This works flawlessly. However, when I want to insert or retrieve values from theArray
, something goes wrong. Here's an excerpt from another file in my app:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[[prefs objectForKey:@"theArray"] setValue:@"This is a value" forKey:@"aValue"];
NSLog(@"%@", [[prefs objectForKey:@"theArray"] valueForKey:@"aValue"]);
I would expect to see "This is a value" in the console when the code has run, but instead I get this:
2011-08-08 18:35:17.503 MyApp[7993:10d03] (
)
How come the array is empty? I've tried the same thing using an NSArray with the same result.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当你将可变对象存储到 NSUserDefaults 时,它会存储它的不可变副本,因此你不能像这样直接更改它。您必须从默认值中获取可变副本,更改它,然后将其设置回来,替换默认值中的旧对象。
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.