I'm creating a simple double value, saving it as NSUserDefault and trying to recover it...but it doesn't.
- (IBAction)try:(id)sender {
double value = 42.00;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setDouble:value forKey:#"kDoubleKey"];
// NSLog(#"loading %f",myDouble);
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSUserDefaults *fetchDefaults = [NSUserDefaults standardUserDefaults];
double intValue = [fetchDefaults doubleForKey:#"kDoubleKey"];
NSLog(#"douvle retrieve %f",intValue);
}
Do not forget to synchronise whenever you save something to the defaults:
put this at the end of your try method
[[NSUserDefaults standardUserDefaults]synchronize];
Here is what apple says about this: Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.
Related
I wanted to know how can I save a user's input when the user enters something from his mobile phone in the UITextField?
If I just use the text field and run the app I can enter data in the text field but when I close the application the data is gone. So how can I store that data permanently and show it again after the application is closed and reopened. Is there any way to save it?
At first, you should save the text when user did editing before user close the application(e.g. saved by NSUserDefaults):
self.yourTextView.delegate = self;
- (void)textViewDidChange:(UITextView *)textView
{
if (textView.markedTextRange == nil)
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:textView.text forKey:#"userText"];
[defaults synchronize];
}
}
Then, load the text that user saved before when user open your application again:
- (void)viewDidLoad
{
[super viewDidLoad];
self.yourTextView.text = [[NSUserDefaults standardUserDefaults]objectForKey:#"userText"];
}
We can save data into 3 data base
If you want to store single data into db, you can use
NSUserDefault
For store
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:textView.text forKey:#"textviewdata"];
[defaults synchronize];
For Retrieve
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *strTextViewText = [NSString stringWithFormat:#"%#",[defaults objectForKey:#"textviewdata"]];
Then Store a larger amount of data,we can use
SQLite
CoreData
Here are some ways to save data inside application.
create local database using sqlite or coredata both provides facilty to save data locally and before use please find the different situations to use these databases.
using NSUserDefaluts but not recomemded because NSUserDefaults aren’t meant to store sensitive information for more information see imp link see example also if you still.
To store data using NSUserDefaluts:
[[NSUserDefaults standardUserDefaults]setObject:self.textfield.text forKey:#"yourKey"];
To get data anywhere inside app:
object = [[NSUserDefaults standardUserDefaults] valueForKey:#"yourKey"];
Try with this:
-(void)viewDidDisappear:(BOOL)animated
{
[[NSUserDefaults standardUserDefaults]setObject:self.urtextfield.text forKey:#"savedtext"];
}
-(void)viewWillAppear:(BOOL)animated
{
self.urtextfield.text = [[NSUserDefaults standardUserDefaults]objectForKey:#"savedtext"];
}
I stored some setting for the peripheral that connected to the iOS device, but I want to add a button for the user to delete this peripheral, this means I must delete all setting related to this peripheral.
The store for this is simple using NSData:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:self.appDelegate.defaultBTServer.selectPeripheralInfo];
[defaults setObject:encodedObject forKey:self.appDelegate.defaultBTServer.selectPeripheralInfo.uuid];
[defaults synchronize];
But how to delete the setting related to this selectPeripheralInfo.uuid?
I found the
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObjectForKey:application.defaultBTServer.selectPeripheralInfo.uuid];
cannot work.
It looks like you might not be using the same key to add and remove the data. To add, you used:
self.appDelegate.defaultBTServer.selectPeripheralInfo.uuid
but to remove the data you used:
application.defaultBTServer.selectPeripheralInfo.uuid
If the values of those expressions aren't exactly the same, you won't be able to remove the data that you added because, obviously, the key will be wrong. So, check that.
Also, make sure that you call [defaults synchronize] after removing to update the defaults in storage.
I have created a Prefs Controller class, which dose what it says controlls my prefs values. I have two specific values in my prefs both strings one that's called installSelected and the other called finishSelected, I setting them as a string that's either T or F...
When the app first starts I create the new prefs and the values are set to F automatically as those are their default values in the plist bundle. Then later in the app I overwrite installSelected to T. When I restart the application it returns the correct value as T. Then I write over it again using F. Again I restart but when I read the values this time it still shows T when it should be F.
I have debugged this and I am just not sure why it's not saving the value.
This is what my prefController method looks like that is used to write the new values:
- (void) writeBool:(NSString *)name MyBool:(NSString *)myboolString {
prefs = [NSUserDefaults standardUserDefaults];
if ([name isEqualToString:#"InstallsSelected"]) {
[prefs setObject:myboolString forKey:name];
}
else if ([name isEqualToString:#"FinishSelected"]) {
[prefs setObject:myboolString forKey:name];
}
[prefs synchronize];
}
I call the above method like this
[prefsController writeBool:#"InstallsSelected" MyBool:#"F"];
It just makes no sense that it's not working as I am able to change it from F to T but not back if needed and none of the code is different. What might be causing this problem?
Why are you using strings instead of bool values?
You have to set your boolean by using:
// Notice setBool
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"pref"];
and call synchronize after it:
[[NSUserDefaults standardUserDefaults] synchronize];
To retrieve the value, you call:
// Notice boolForKey
if(![[NSUserDefaults standardUserDefaults] boolForKey:#"pref"]) {
// False
} else {
// True
}
To register default prefs, use:
NSDictionary *appDefaults = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], #"pref1",
[NSNumber numberWithBool:YES], #"pref2",
nil];
NSUserDefaults * prefs = [NSUserDefaults standardUserDefaults];
[prefs registerDefaults:appDefaults];
Are you on the simulator or a real device? I have had serious problems getting the sync right in the Simulator. It turns out that if you just do a rebuild from xCode, the user preferences are not saved. They are saved if you bring the app to the background in the Simulator (press cmd-shift-H).
Also it helps to NSLog as much as possible to see what is written in the prefs.
I am using the NSUserDefaults Class to store some data but I have a normal conflict concerning the initialization.
I mean:
In my Class A in the didViewLoad method, I have set my NSUserDefaults data and afterwards in my Class B, in the didViewLoad, I want to get my NSUserDefaults data.
I have seen with the breakpoints that during the first-run-application, all the didViewLoad() of the application are performed, so I would like to put a condition in the viewDidLoad() of my Class B for the first-run-application to avoid random data initialization.
Have we got a keyword in Objective-C's framework instead of using static variable ?
eg:
ClassA--> didViewLoad():
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:kdataText forKey:#"udVariable"];
ClassB-> didViewLoad():
And:
ClassB--> didViewLoad():
if (!first_run){ // first_run --> KEYWORD FRAMEWORK???
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *var = [defaults objectForKey:#"udVariable"];
}
The key is to call registerDefaults even earlier, like in main or in the app delegate's applicationDidFinishLaunching:. From an app of mine:
[[NSUserDefaults standardUserDefaults] registerDefaults:
#{#"cardMatrixRows":#4, #"cardMatrixColumns":#3}];
Now there is a default default, as it were, and the order of events / view controllers no longer matters.
Swift 4:
Add this code to AppDelegate within didFinishLaunchingWithOptions:
UserDefaults.standard.register(defaults: ["cardMatrixRows": NSNumber(value: 4), "cardMatrixColumns": NSNumber(value: 3)])
Just check if
[defaults objectForKey:#"udVariable"] != nil
You can also use macro #define.
I want to display a help message on a view controller when the app is installed and opened for the very first time ONLY.
Is there a method I can use to do this?
You can display the help message once, and then store a boolean value in NSUserDefaults to indicate that it should not be shown again:
NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
BOOL appHasBeenLaunchedBefore = [userDefaults boolForKey:#"HasBeenLaunched"];
if (!appHasBeenLaunchedBefore)
{
[self showHelpMessage];
}
[userDefaults setBool:YES forKey:"HasBeenLaunched"];
Use Grand Central Dispatch's dispatch_once() and check some persistent storage.
static dispatch_once_t pred;
dispatch_once(&pred,^{
NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
BOOL hasLaunched = [userDefaults boolForKey:kAppHasLaunched];
if (!hasLaunched) {
[self showFirstLaunchMessage];
[userDefaults setBool:YES forKey:kAppHasLaunched];
}
});
This is the easiest way to ensure code only gets run once in your app per launch (in this case the block will only be executed once). More information about this is in the Grand Central Dispatch Reference. In this block you simply need to check some persistent storage, such as your preferences, to see if your app has ever launched before and display a message as appropriate.
Use a key in the user defaults. For example:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
BOOL launchedBefore = [userDefaults boolForKey:#"hasRunBefore"];
if(!hasRunBefore)
{
NSLog(#"this is my first run");
[userDefaults setBool:YES forKey:#"hasRunBefore"];
}
The user defaults are backed up by iTunes, so it'll normally be the user's first launch rather than the first launch per device.
EDIT: this is explicitly the same answer as e.James gave before me. The 'other answers have been posted' bar failed to appear. I'll leave it up for the example code but don't deserve credit fir a first answer.