NSUserDefaults problem - iphone

I have two views.In One view when i click on custom button it goes into second view,In that i have text view and that data must store in temperary memory so i used following code:
NSString *myString=txtvNote.text;
[txtvNote setText:#""];
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults) {
[standardUserDefaults setObject:myString forKey:#"note"];
[standardUserDefaults synchronize];
}
and when i go back on 1st view by clicking on the add button it will save into database for that i used following code:
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSString *val = nil;
if (standardUserDefaults)
val = [standardUserDefaults objectForKey:#"note"];
NSLog(#"Note::%#",val);
and then pass this value in insert query.
Now my problem is when i left that value blank,it takes the value which is inserted before.

sequence must be like this
//first set text to something
[txtvNote setText:#""];
//then use that text
NSString *myString=txtvNote.text;

myString is a pointer to the text in txtvNote. So if you set that text to #"" then myString will be empty as well. To preserve the value of txtvNote at the time of assignment use copy or reset the text after saving it:
NSString *myString=[[txtvNote.text copy] autorelease];
[txtvNote setText:#""];
....

That's the way NSUserDefaults works - every value is stored in your app's preferences, and like any other collection in Obj-C, it doesn't take nil values. Use instance of NSNull class or empty string. Or even better - use intermediate controller to store values and use key-value observing in your first view.

Related

storing data common to more than one view controllers

I know there are many ways for storing data like property list,archiving etc..but other than that is there any other way for storing very small amount of data,which is common to different view controllers(like a common class for storing all the data)?.
Try this
NSUserDefaults
when you want to save small amounts of data such as High Scores, Login Information, and program state.
saving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving an NSString
[prefs setObject:#"TextToSave" forKey:#"keyToLookupString"];
// saving an NSInteger
[prefs setInteger:42 forKey:#"integerKey"];
// saving a Double
[prefs setDouble:3.1415 forKey:#"doubleKey"];
// saving a Float
[prefs setFloat:1.2345678 forKey:#"floatKey"];
[prefs synchronize];
Retrieving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *myString = [prefs stringForKey:#"keyToLookupString"];
// getting an NSInteger
NSInteger myInt = [prefs integerForKey:#"integerKey"];
// getting an Float
float myFloat = [prefs floatForKey:#"floatKey"];
We can do it by creating a singleton class and shared instance
Yes, you can define the required fields in form of an array. Now make sure that the form will provide you an identity and there is some validation through session etc. A a hook to your controller to sense the form submission every time with a particular flag (hidden). So the tablename and CRUD instruction will be provided to this function and every common CRUD functionality will be handled by this single function. By defining the required fields will let you ignore the extra ones like input buttons and many hidden fields.
use NSUserDefault to store values.
Yes you can declare in forms of NSMutableArray or NSMutableDictionary and access it any Viewcontrollers. You need to create a file as NSObject class and in
.h
+(NSMutableDictionary *)ImageCollection;
in .m file
+(NSMutableDictionary *)ImageCollection
{
static NSMutableDictionary *thestring =nil;
#synchronized([Global class]) // in a single threaded app you can omit the sync block
{
if (thestring ==nil) {
thestring=[[NSMutableDictionary alloc]init];
}
}
return thestring;
}
In any View Controllers include that NSObject class file
[[Global ImageCollection]setObject:#"Sample" forKey:#"Dictionary"]; //just example you can save string,image,array anything as you like
Hope this helps .. !!!
Use shared memory, to store and share common data between views.

adding an item to at array in NSUserdefault

I am new to iOS development and could not find a way to solve this problem:
I have an app that has two views: one where the user enters some information (say a string), and another view where there is a tableview that includes all the strings that were ever entered (like a history view).
What I am trying to find is a good way to store the input string, then load it into the table view data source once the user switches to the history. I tried to use NSUserdefault but with not much success. Just getting messed up with the data structures, etc.
Here is what I am doing on the main view (where the user enters the input string):
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *arr1 = [[NSMutableArray alloc] init];
arr1 = [defaults arrayForKey:#"historyNames"];
[arr1 addObject:string];
[defaults setObject:arr1 forKey:#"historyNames"];
From some reason I get a warning where I read to arr1, and honestly, I doubt that should work anyway.
Can anyone suggest how I could modify this to work properly and achieve what I am looking for?
Thanks.
[defaults arrayForKey:#"historyNames"];
Will return nil if you never initialized and saved an array for that key in NSUSerDefaults.
If you initialize and array and set it once (look up how to initialize default values for NSUserDefaults), it will return a proper array.
Then you can just do
NSMutableArray *arr1 = [NSMutableArray arrayWithArray:[[defaults arrayForKey#"historyNames"]];
Depending on how many elements this array will have, you may be better off using Core Data. Using user defaults is not very efficient for many/large values, just for small settings and things like that.
When your application starts up, look in user defaults to see if you have an array object already from the last time you used it. If there isn't one, call alloc and init for arr1. (You don't want to call it if you're accessing it from defaults.)
NSMutableArray * arr1;
arr1 = (NSMutableArray *) [defaults objectForKey:#"historyNames"];
if (!arr1) {
arr1 = [[NSMutableArray alloc] initWithCapacity:20];
}
In your main view, just add the input string, and save the defaults.
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject: arr1 forKey: #"historyNames"];
[prefs synchronize];

NSUserDefaults - storing and retrieving data

I have some data that's been stored using NSUserDefaults in one view and then being displayed in another view. The issue I'm having is that when the user changes the data and then returns to the view where the data is displayed (in a UILabel), the data that was first saved is displayed instead of the newer saved text.
I think I need to do something with viewDidAppear perhaps, so that every time the view appears the newest saved data is displayed.
here's the code that Im displaying the NSUserDefaults stored info on a UILabel:
NSString *aValue = [[NSUserDefaults standardUserDefaults] objectForKey:#"myTextFieldKey"];
NSLog(#"Value from standardUserDefaults: %#", aValue);
NSLog(#"Label: %#", myLabel);
myLabel.text = aValue;
if someone could point me in the right direction that would be great,
thanks
Put this text in
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear: animated];
NSString *aValue = [[NSUserDefaults standardUserDefaults] objectForKey:#"myTextFieldKey"];
NSLog(#"Value from standardUserDefaults: %#", aValue);
NSLog(#"Label: %#", myLabel);
myLabel.text = aValue;
}
And in your "edit" view in - viewWillDisappear: save changes in NSUserDefaults
When saving data to NSUserDefaults, it doesnt immediately write to the Persistent Storage. When you save data in NSUserDefaults, make sure you call:
[[NSUserDefaults standardUserDefaults] synchronize];
This way, the value(s) saved will immediately be written to Storage and each subsequent read from the UserDefaults will yield the updated value.
Do not forget the use synchronize when you set some value
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:YOUR_VALUE forKey:#"KEY_NAME"];
[defaults synchronize];
Now you can place your code in viewWillAppear method to retrieve the value from defaults, this will help you fetch the currentsaved value for your desired key.
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSString* strValue = [defaults objectForKey:#"KEY_NAME"];
myLabel.text = strValue != nil ? strValue : #"No Value";
Hope it helps
In Swift we can do it following way:
To save value:
let defaults = UserDefaults.standard
defaults.set(YOUR_VALUE, forKey: "YOUR_KEY_NAME")
To get value:
let defaults = UserDefaults.standard
let data = defaults.objectForKey("YOUR_KEY_NAME")
For more details visit:
https://www.hackingwithswift.com/example-code/system/how-to-save-user-settings-using-userdefaults

Saving and Retrieving UILabel value with NSUserDefaults

I trying to save UILabel value to NSUserDefaults. I did IBAction with this code:
-(IBAction)saveData:(id)sender {
NSString *resultString = label.text;
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:resultString forKey:#"result"];
[prefs synchronize];
}
Then, I connect it to button with Touch Up Inside.
What log shows after I pressed the button:
result = 0;
When I pressed a second time, then it works.
result = "28.34";
What I'm doing wrong and how can I retrieve a result?
EDIT
With this code I display result in log. I put it to same action.
NSLog(#"%#", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
Your code looks correct, so the issue is probably not the function you posted but rather the code that contains your NSLog. You might be logging the value in a way that misses the first time it gets set.
Your log statement should be
NSLog(#"%#",[[NSUserDefaults
standardUserDefaults]
objectForKey:#"result"]);
This should be after you set the object in NSUserDefaults.
Add this to your applicationDidFinishLaunching in appDelegate or in init method in viewController(you have to create one) :
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if(prefs == nil)
{
[prefs setObject:#"anything" forKey:#"result"];
[prefs synchronize];
}

textfield content in an iphone

As iam new the iphone development, i had created some textfields ,on click of save button it gets saved to a xml file ,and get disappears in the text field.On the next login, how to get the previously entered data in the same text field,so that i can modify the same data entered in the previous log in
thank you in advance
Read the xml file and set this to the textfield, textfield.text = #"your String";
To get previously entered data, you have to save them.
For this when user tap on save button you can save the value of each text field to NSUserDefaults for a key and when you want to get data you can get for that key.
To save-
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[textfield text] forKey:#"username"];
To get -
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *str = [defaults objectForKey:#"username"];