在 NSUserDefaults 中保存值时出现问题
我将其作为我的 viewDidLoad
:
- (void)viewDidLoad
{
[super viewDidLoad];
if (defaults == [cells objectAtIndex:0])
{
NSString * myFile = [[NSBundle mainBundle]pathForResource:@"cells" ofType:@"plist"];
cells = [[NSMutableArray alloc]initWithContentsOfFile:myFile];
}
else
{
[defaults stringForKey:@"string1"];
}
}
对于我的 viewWillDisappear
我有:
-(void)viewWillDisappear:(BOOL)animated
{
string1 = [cells objectAtIndex:0];
[defaults setObject:string1 forKey:@"string1"];
}
但我无法保存要保存的数据。有谁知道我做错了什么?
I have this as my viewDidLoad
:
- (void)viewDidLoad
{
[super viewDidLoad];
if (defaults == [cells objectAtIndex:0])
{
NSString * myFile = [[NSBundle mainBundle]pathForResource:@"cells" ofType:@"plist"];
cells = [[NSMutableArray alloc]initWithContentsOfFile:myFile];
}
else
{
[defaults stringForKey:@"string1"];
}
}
And for my viewWillDisappear
I have:
-(void)viewWillDisappear:(BOOL)animated
{
string1 = [cells objectAtIndex:0];
[defaults setObject:string1 forKey:@"string1"];
}
But I cannot get the data to be saved. Does anyone know what I'm doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
defaults
应该是NSUserDefaults
的实例:因此,
if (defaults == [cells objectAtIndex:0])
不是有效的代码行除非你摆弄内存,否则它永远不会相等。否则,代码看起来不错。
defaults
should be an instance ofNSUserDefaults
:Therefore,
if (defaults == [cells objectAtIndex:0])
is not a valid line of code and it will never be equal unless you're fiddling with the RAM.Otherwise, the code looks fine.
您是否在某处将默认值设置为
[NSUserDefaults standardUserDefaults]
?另外,为什么要将它与 cells 数组中的第一个对象进行比较?看起来很奇怪。否则你的想法是正确的。确保 viewWillDisappear 方法确实被调用。您也可以调用
[NSUserDefaults Synchronize]
来立即保存更改。最后一件事,您没有在 else {} 块中执行任何操作。您需要将
[defaults stringForKey:@"string1"];
的值分配给变量才能使用它。Are you setting defaults to
[NSUserDefaults standardUserDefaults]
somewhere? Also, why are you comparing it to the first object in the cells array? Seems strange.You've otherwise got the idea correct. Make sure the viewWillDisappear method is actually getting called. Also you can call
[NSUserDefaults synchronize]
to save the changes immediately.One last thing, you aren't doing anything in that else {} block. You need to assign the value of
[defaults stringForKey:@"string1"];
to a variable to use it.