我正在尝试使用此 Apple 演练开发基于文档的 Mac 应用程序,但在保存文件时遇到问题(最后一步)。尝试保存文件后出现的错误是:无法将文档“未命名”保存为“-我正在尝试使用新文件名-”
我用谷歌搜索并没有找到这个错误的任何结果。我重新检查了代码,对教程来说一切似乎都很可靠。我想知道是否有人对这里可能出现的问题有任何直觉。
我的主要课程的代码是:
#import "MyDocument.h"
@implementation MyDocument
- (id)init
{
self = [super init];
if (self) {
if (mString == nil) {
mString = [[NSAttributedString alloc] initWithString:@""];
}
}
return self;
}
- (NSAttributedString *) string { return [[mString retain] autorelease]; }
- (void) setString: (NSAttributedString *) newValue {
if (mString != newValue) {
if (mString) [mString release];
mString = [newValue copy];
}
}
- (void) textDidChange: (NSNotification *)notification {
[self setString: [textView textStorage]];
}
- (NSString *)windowNibName
{
// Override returning the nib file name of the document
// If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this method and override -makeWindowControllers instead.
return @"MyDocument";
}
- (void)windowControllerDidLoadNib:(NSWindowController *) aController
{
[super windowControllerDidLoadNib:aController];
if ([self string] != nil) {
[[textView textStorage] setAttributedString: [self string]];
}
}
- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError
{
BOOL readSuccess = NO;
NSAttributedString *fileContents = [[NSAttributedString alloc]
initWithData:data options:NULL documentAttributes:NULL
error:outError];
if (fileContents) {
readSuccess = YES;
[self setString:fileContents];
[fileContents release];
}
return readSuccess;
}
- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError
{
NSData *data;
[self setString:[textView textStorage]];
NSMutableDictionary *dict = [NSDictionary dictionaryWithObject:NSRTFTextDocumentType
forKey:NSDocumentTypeDocumentAttribute];
[textView breakUndoCoalescing];
data = [[self string] dataFromRange:NSMakeRange(0, [[self string] length])
documentAttributes:dict error:outError];
return data;
}
头文件:
#import <Cocoa/Cocoa.h>
@interface MyDocument : NSDocument
{
IBOutlet NSTextView *textView;
NSAttributedString *mString;
}
- (NSAttributedString *)string;
- (void) setString: (NSAttributedString *)value;
@end