在 NSUserDefaults 中保存值时出现问题

发布于 2024-11-25 10:52:29 字数 643 浏览 1 评论 0原文

我将其作为我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

奢欲 2024-12-02 10:52:29

defaults 应该是 NSUserDefaults 的实例:

defaults = [NSUserDefaults sharedUserDefaults];

因此,if (defaults == [cells objectAtIndex:0]) 不是有效的代码行除非你摆弄内存,否则它永远不会相等。

否则,代码看起来不错。

defaults should be an instance of NSUserDefaults:

defaults = [NSUserDefaults sharedUserDefaults];

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.

路还长,别太狂 2024-12-02 10:52:29

您是否在某处将默认值设置为 [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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文