1
我已阅读并观看了iPhone OS/iOS SDK中的NSUserDefaults
许多教程,但似乎无法让我自己的实现工作。为什么我的NSUserDefaults实现不能在iOS 4下工作?
现在,我正在构建一个简单的计数应用程序,我希望在应用程序加载时加载最后计数的数字。 然而,NSUserDefaults
有一个不同的想法。有谁知道为什么我的偏好加载方法不断返回(null)
在NSLog
?
在此先感谢! :)
CounterViewController.m(有删节)
- (void)viewDidLoad {
// yadda yadda yadda interface setup here...
if ([self retrieveCount] == 0) {
count = 0;
} else {
count = [self retrieveCount];
NSString *temp = [[NSString alloc] initWithFormat:@"%@", count];
[label setText:temp];
[temp release];
}
[super viewDidLoad];
}
int count = 123; //whatever it might be when the user exits the application, set every time the "+" or "-" is tapped
- (void)writeCount {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setInteger:count forKey:@"countKey"];
[prefs synchronize];
}
- (int)retrieveCount {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs synchronize];
int loaded = [prefs integerForKey:@"countKey"];
NSLog(@"%@", loaded);
return loaded;
}
CounterAppDelegate.m
- (void)applicationWillTerminate:(UIApplication *)application {
/*
Called when the application is about to terminate.
See also applicationDidEnterBackground:.
*/
[CountrViewController writeCount];
}
(因为我只能从一个关键字进行检索的值,我决定没有任何输入的方法。)
如果这有什么困惑,请让我k现在!我会很乐意提供澄清。
作为一个方面说明,同步会自动以周期性间隔调用,它非常可靠我从来没有调用它,但为了保存,在应用程序终止之前我会调用它。 – 2010-08-14 04:46:46