1

I have been playing around with Apple's sample code - UserDefaults - http://developer.apple.com/library/mac/#samplecode/UserDefaults/Introduction/Intro.html - and I haven't been able to get it working with an instance of NSTextView and by removing the record button and I was therefore wondering how to get NSUserDefaults to automatically store the contents of an NSTextView.

Thanks in advance!

1 Answer 1

0

There's no way to store it automatically. Here's a simple way to save contents by subclassing NSTextView:

@interface myTextView : NSTextView 
@end

@implementation myTextView

- (void)awakeFromNib
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString    *string = nil;
    if (userDefaults) 
        string = [userDefaults objectForKey:@"Prefs"];
    if ([string length])
        [self setString:string];
}

- (void)didChangeText
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

    if (userDefaults) {
        [userDefaults setObject:[self string] forKey:@"Prefs"];
    }
}

@end

EDIT

Removed synchronize.

5
  • Wait, do you have/know of any source that that demonstrates this? Thanks a lot for your time!
    – user437038
    Aug 5, 2011 at 9:57
  • synchronize should not be called like here. From the docs: The synchronize method, which is automatically invoked at periodic intervals, keeps the in-memory cache in sync with a user’s defaults database. And: Because this method (synchronize) 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.
    – nacho4d
    Aug 5, 2011 at 10:26
  • Ok... could you suggest alternative code and/or a working example from somewhere, much appreciated!
    – user437038
    Aug 5, 2011 at 11:22
  • @dbramhall:"Wait, do you have/k... demonstrates this?" - no. i copied this code from my project and modyfied it a bit. @dbramhall:"Ok... could you suggest alternative code and/or a worki..." - i forgot to remove this line: [userDefaults synchronize];
    – VenoMKO
    Aug 5, 2011 at 11:31
  • @nacho4d: Thx. I forgot to remove it from here.
    – VenoMKO
    Aug 5, 2011 at 11:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.