Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

UITextView (save Text)

I am trying to save characters in a UITextView. In other words if someone were to type something in a UITextView it would stay there till deleted (even if the application is closed). How would I do this? (Note: I have never used a UITextView before).

2 Answers

Neil Shweky
Neil Shweky
5,022 Points

oh sorry about that...

Here's the code:

The .h file:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITextViewDelegate>

@property (nonatomic, strong) NSString *string;
@property (nonatomic, strong) IBOutlet UITextView *textView;
@end

The .m file:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.string = [[NSUserDefaults standardUserDefaults] objectForKey:@"text"];
    self.textView.text = self.string;

    self.textView.delegate = self;

    [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(updateString) userInfo:nil repeats:YES];

}

//Saves the updated string in the user defaults
-(void) updateString{


    [[NSUserDefaults standardUserDefaults] setObject:self.textView.text forKey:@"text"];
}


//Dismisses the keyboard
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

    if([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }

    return YES;
}

@end

If you have any problems...

Remember to call the synchronize method after using the NSUserDefaults so that the value can be saved immediately.

Uh your dropbox file was deleted or something. If you could just copy and paste some code snippet into the answer column that would be great! Thanks :)