2010-08-14 82 views
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现在!我会很乐意提供澄清。

回答

3

首先,在您读取默认设置之前,您不需要拨打-synchronize,只有在您写完之后才能读取。 您的NSLog实际上可能是此处的罪魁祸首 - 尝试%d而不是%@%@用于打印对象,如NSStringNSNumber;一个int是一个原始类型。

+2

作为一个方面说明,同步会自动以周期性间隔调用,它非常可靠我从来没有调用它,但为了保存,在应用程序终止之前我会调用它。 – 2010-08-14 04:46:46

相关问题