我使用下面的代码(来自AppDelegate文件)将登录的Facebook用户名保存到NSUserDefaults首选项。代码检索用户名并将其输出到控制台就好了。当我尝试在另一个视图控制器中执行相同的操作时,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);
}
};
以下是其他视图控制器中无法正常工作的代码:
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)
答案 0 :(得分:2)
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"];
答案 1 :(得分:1)
尝试:
[[NSUserDefaults standardUserDefaults] setValue:newStr forKey:@"Username"];
用于设置和:
[[NSUserDefaults standardUserDefaults] valueForKey:@"Username"];
获得它。没有进口,什么都没有!
答案 2 :(得分:0)
常见的错误是忘记或不知道保存默认值.. 致电:
[[NSUserDefaults standardUserDefaults] synchronize];
这会将您的默认值写入文件,以便您下次检索它们。