NSUserDefaults不接受设置

时间:2014-03-24 14:20:04

标签: ios7 xcode5

我很擅长在Objective C中编码并使用设置包,但这是我编码的内容。

    // Set the application defaults
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@"YES"
                                                        forKey:@"gameSave"];
    [defaults registerDefaults:appDefaults];
    [defaults synchronize];   
    // Get user preference
    gameSave = [defaults boolForKey:@"saveGame"];
    NSLog(@"Save Game = %@", gameSave ? @"YES" : @"NO");

这是我的设置包:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"       "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>PreferenceSpecifiers</key>
<array>
    <dict>
        <key>Title</key>
        <string>XXXXXXXXXXXXX</string>
        <key>Type</key>
        <string>PSGroupSpecifier</string>
        <key>FooterText</key>
        <string>www.xxxxxxxxxxxx.com</string>
    </dict>
    <dict>
        <key>DefaultValue</key>
        <true/>
        <key>Key</key>
        <string>gameSave</string>
        <key>Title</key>
        <string>Save Game</string>
        <key>Type</key>
        <string>PSToggleSwitchSpecifier</string>
    </dict>
</array>
<key>StringsTable</key>
<string>Root</string>
</dict>
</plist>

测试时,gameSave值为NO或false。有人能指出我的解决方案吗?感谢。

2 个答案:

答案 0 :(得分:0)

@"YES"NSString,而不是包含布尔值的NSNumber

您想要@YES代替:

NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@YES
                                                    forKey:@"gameSave"];

或相同,更短:

NSDictionary *appDefaults = @{@"gameSave": @YES};

编辑:如果你这样做了?这个?

// Set the application defaults -- only if not written yet
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:@"gameSave"] == nil)
{
    [defaults setBool:YES forKey:@"gameSave"];
    [defaults synchronize];
}

// Get user preference
gameSave = [defaults boolForKey:@"gameSave"];
NSLog(@"Save Game = %@", gameSave ? @"YES" : @"NO");

答案 1 :(得分:0)

这应该是直截了当的:

保存布尔:

// Write the value to NSUserDefault
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:YES forKey:@"gameIsSaved"];
[defaults synchronize];

检索布尔值

//Read the value from NSUserDefault
bool gameIsSaved = [defaults boolForKey:@"gameIsSaved"];
NSLog(@"gameIsSaved = %@", gameIsSaved ? @"YES" : @"NO");