Ashim
Ashim

Reputation: 927

How to save user's input in UITextField?

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?

Upvotes: 1

Views: 3729

Answers (4)

CHwang
CHwang

Reputation: 163

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"];
}

Upvotes: 2

vaibhav
vaibhav

Reputation: 4096

Here are some ways to save data inside application.

  1. 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.
  2. 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"];

Upvotes: 1

user3182143
user3182143

Reputation: 9609

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

Upvotes: 1

Minkle Garg
Minkle Garg

Reputation: 751

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"];
    }

Upvotes: 0

Related Questions