同步后NSUserDefaults未保存

时间:2016-04-07 13:53:54

标签: ios objective-c nsuserdefaults

我的应用程序中有以下代码

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:kArchivedUsername forKey:userID];
    [defaults synchronize];
    NSLog(@"saved: %@", [defaults stringForKey:kArchivedUsername]);

然而,输出是这样的:

2016-04-07 15:50:44.560 BP (Test)[18357:464518] saved: (null)

有人可以告诉我为什么以及我能做些什么呢?

4 个答案:

答案 0 :(得分:5)

你有关键和价值逆转:

[defaults setObject:userID forKey:kArchivedUsername];

感谢:Teja Nandamuri

答案 1 :(得分:4)

这是您的代码

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:kArchivedUsername forKey:userID];
[defaults synchronize];
NSLog(@"saved: %@", [defaults stringForKey:kArchivedUsername]);

了解如何在2个地方forKey:userIDstringForKey:kArchivedUsername

中指定密钥

最好仔细检查一下

答案 2 :(得分:0)

尝试这个简单的

//NSUserDefault For Save:-

 [[NSUserDefaults standardUserDefaults]setValue:usernamestr1 forKey:@"Usernamestr1"];

//对于Fatch: -

 Cathing_Name_str3 =[[NSUserDefaults standardUserDefaults]objectForKey:@"Usernamestr1"];

答案 3 :(得分:0)

[defaults stringForKey:kArchivedUsername] 

In this line pass your Key instead of Value like. Please follow below code.

[defaults stringForKey:userID] 
o/p 2016-04-07 23:13:08.723 segmentTintColor[27646:662430] saved: kArchivedUsername