Storing the contents of NSTextView with NSUserDefaults
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
.
精彩评论