How to set initial values for NSUserDefault Keys?
You should use the registerDefaults
method of NSUserDefaults
. Prepare a plist file in your bundle that contains the default preferences and then use that plist to register the defaults.
NSString *defaultPrefsFile = [[NSBundle mainBundle] pathForResource:@"defaultPrefs" ofType:@"plist"];
NSDictionary *defaultPreferences = [NSDictionary dictionaryWithContentsOfFile:defaultPrefsFile];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultPreferences];
You have to execute this code on every launch of your app. It will add these values to a separate domain in the user defaults hierarchy. Whenever your app's user defaults don't provide a value for a certain key, NSUserDefaults
will fall back to this domain and retrieve the value from there.
NSUserDefaults - how to set start value?
You can set initial values using registerDefaults:
which takes an NSDictionary
of all your initial keys and their respective values. Example:
[[NSUserDefaults standardUserDefaults] registerDefaults:@{ kSoundEnabled : @YES }];
NSUserDefaults: how to get only the keys I've set
Elegant approach
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
NSDictionary *dict = [defaults persistentDomainForName:bundleIdentifier];
File approach:
NSString *bundleIdentifier = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"];
NSString *path = [NSString stringWithFormat:@"~/Library/Preferences/%@.plist",bundleIdentifier];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[path stringByExpandingTildeInPath]];
NSArray *keys = [dict allKeys];
Tested with sandboxing.
NSUserDefaults key initialization when app starts for the first time
Try this,
let defaults = NSUserDefaults.standardUserDefaults()
if (defaults.objectForKey("fasterDemo")) {//no need to use '==nil'
defaults.setBool(true, forKey: "fasterDemo")
}
and,
let demo = defaults.boolForKey("fasterDemo")
var timerSpeed: Double = 1
if (demo) {//same as 'demo == true'
timerSpeed = 0.001
}
else {
timerSpeed = 1
}
timer = NSTimer.scheduledTimerWithTimeInterval(timerSpeed, target: self, selector: Selector("countdownTimer"), userInfo: nil, repeats: true)
Note the stringForKey
has been replaced with boolForKey
NSUserDefaults set the default value of integer variable to empty
Well, this line:
int port = [defaults integerForKey:@"port"];
will always assign some value to port
.
Also, this:
NSString *portString = [NSString stringWithFormat:@"%lu",(unsigned long)port];
will always produce a non-empty string. There's no value you could pass for a %lu
specifier that will produce an empty string.
So, what you want to do is ask for the object that's stored in the preferences, without converting it to a integer value:
id portObject = [defaults objectForKey:@"port"];
if (portObject)
{
NSInteger port;
if ([portObject respondsToSelector:@selector(integerValue)])
port = [portObject integerValue];
else
{
// portObject is some unexpected class of object, such as an array or dictionary. Take some appropriate action. Or:
port = 0;
}
portField.text = [NSString stringWithFormat:@"%ld", (long)port];
}
else
{
// There was no value either stored or registered for the key "port"
portField.text = @"";
}
Note that for this to work, you must not have registered a default value for the "port" key using -[NSUserDefaults registerDefaults:]
.
Setting default settings in NSUserDefaults. What I do wrong?
You forgot to write this after to change something in NSUserDefaults
[defaults synchronize];
How to deal with non-optional values in NSUserDefaults in Swift
Register the user defaults in AppDelegate, the best place is awakeFromNib
or even init
. You can provide custom default values for every key.
override init()
{
let defaults = UserDefaults.standard
let defaultValues = ["key1" : 12, "key2" : 12.6]
defaults.register(defaults: defaultValues)
super.init()
}
Then you can read the values from everywhere always as non-optionals
let defaults = UserDefaults.standard
myVariable1 = defaults.integer(forKey: "key1")
myVariable2 = defaults.double(forKey:"key2")
Related Topics
Ios: Capture Image from Front Facing Camera
Disable Magnification Gesture in Wkwebview
How to Figure Out Which Url Is Being Blocked by App Transport Security
Push Notifications Not Being Received on iOS 10, But Working on iOS 9 and Before
Loading Viewcontroller from Xib File
How to Remove Tmp Directory Files of an iOS App
How to Get Notified of Uitableviewcell Move Start and End
Apn (Apple Push Notification) Payload Size Limit
An Error Occurred Uploading to the Itunes Store
How to Add a Button with Click Event on Uitableviewcell in Swift
iOS Storyboard Passing Data Navigationviewcontroller
Setting Constraints Programmatically
How to Get Managedobjectcontext for Viewcontroller Other Than Getting It from Appdelegate
Decrease the Width of the Last Line in Multiline Uilabel
How Does the Whatsapp Web Client Still Work with the Latest iOS Update (Sdk Version 13.0+)