Developer
Developer

Reputation: 1435

NSUserDefaults problem

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.

Upvotes: 0

Views: 130

Answers (3)

Kyr Dunenkoff
Kyr Dunenkoff

Reputation: 8090

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.

Upvotes: 1

diederikh
diederikh

Reputation: 25281

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:@""];
 ....

Upvotes: 1

sequence must be like this

//first set text to something

 [txtvNote setText:@""];

//then use that text

 NSString *myString=txtvNote.text;

Upvotes: 2

Related Questions