I am trying to save UserDefaults using methods from iOSKit.
I am pretty unclear on using declares but I think I am getting close to making this work.
With Foundation.NSUserDefaults() I want to create a dictionary to set the defaults. (Am I barking up the wrong tree?)
Here is my code.
[code]Dim PrefKey As Foundation.NSString = “Paid”
Dim PrefVal As Foundation.NSString = “True”
Dim PrefKeys As Foundation.NSArray //= Array(PrefKey, “test”) //Stuck here on how to populate array
Dim PrefVals As Foundation.NSArray //= Array(PrefVal, “test”)
Dim UserDefaults As Foundation.NSUserDefaults
Dim UserDefaultsDict As Foundation.NSDictionary
UserDefaultsDict.Constructor(PrefKeys, PrefVals)
UserDefaults.RegisterDefaults(UserDefaultsDict)[/code]
It’s not that complicated. Just declare a property of type NSUserDefaults. I have one in my App class called defaults because I find that convenient and I read somewhere that there is a small overhead/penalty if you repeatedly instantiate it.
Then, to write a boolean property (for example) just do this:
app.defaults.SetBoolForKey(boolValue, keyName)
To read it back, just do this:
boolValue = app.defaults.BoolForKey(keyName)
Hmm… It is not working for me.
I created a property called UserDefaults and in its “Type” field I put “NSUserDefaults”
In the app open event handler I put.
Dim boolVal As Boolean = false
Dim keyName As Text = "Paid"
app.UserDefaults.SetBoolForKey(boolVal, keyName)
I get a NilObjectException and the NSUserDefaults object is Nil.
Sorry @JP Kelly I missed a step. You need to instantiate the class, so just add this in your app open event:
UserDefaults = NSUserDefaults.StandardUserDefaults
Yep it works!
Awesome! Thank you!
Indeed as Jason said, just use StandardUserDefaults. Trying to make your own isn’t the greatest and will just cause headaches down the line.