gpt4 book ai didi

objective-c - 从 NSUserDefaults 检索数据 - 在一个 View 中有效,但在另一个 View 中失败

转载 作者:行者123 更新时间:2023-12-01 19:21:59 25 4
gpt4 key购买 nike

我使用下面的代码(来自 AppDelegate 文件)将登录的 Facebook 用户名保存到 NSUserDefaults 首选项。该代码检索用户名并将其输出到控制台就好了。当我尝试在另一个 View Controller 中做同样的事情时,NSLog 输出返回(null)。

我错过了什么?谢谢你的帮助。

- (void)request:(FBRequest *)request didLoad:(id)result {
if ([result isKindOfClass:[NSDictionary class]]) {
NSDictionary* hash = result;
NSString *username = (NSString*)[hash valueForKey:@"name"];
[[NSUserDefaults standardUserDefaults] setObject:username forKey:@"Username"];
NSLog(@"%@", username);
NSUserDefaults * standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSString *user = [standardUserDefaults stringForKey:@"Username"];
NSLog(@"username from user defs %@",user);
}
};

这是来自其他 View Controller 的代码不起作用:
NSUserDefaults * standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSString *user = [standardUserDefaults stringForKey:@"Username"];
NSLog(@"username from user defs %@",user);
userNameLbl.text = user;

这是日志输出:
username from user defs app delegate my Facebook name
2012-03-30 13:29:20.564 project V2[63339:15803] (null)
2012-03-30 13:29:20.565 project V2[63339:15803] username from user defs app delegate (null)
2012-03-30 13:29:28.620 project V2[63339:15803] username from user defs (null)

最佳答案

NSUserDefaults * standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"Username"];
NSLog(@"username from user defs %@",user);
userNameLbl.text = user;

试试这个(我只改变了一行)
NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"Username"];

编辑
这就是我将内容保存到 NSUserDefaults 的方式;
NSString *theKeyIWantToSave;
NSUSerDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:theKeyIWantToSave forKey:@"SomeKey"];

随时随地我想检索它
NSString *key=[[NSUserDefaults standardUserDefaults] objectForKey:@"SomeKey"];

关于objective-c - 从 NSUserDefaults 检索数据 - 在一个 View 中有效,但在另一个 View 中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9942657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com