开发者

Storing the contents of NSTextView with NSUserDefaults

开发者 https://www.devze.com 2023-03-25 15:51 出处:网络
I have been playing around with Apple\'s sample code - UserDefaults - http://developer.apple.com/library/mac/#samplecode/UserDefaults/Introduction开发者_如何学JAVA/Intro.html - and I haven\'t been abl

I have been playing around with Apple's sample code - UserDefaults - http://developer.apple.com/library/mac/#samplecode/UserDefaults/Introduction开发者_如何学JAVA/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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消