我想将一个NSTextView
对象添加到我的应用程序中,并添加一个操作来打开位于 textView 中的应用程序包中的 .txt 文件。另外 - 我希望可以选择编辑和保存编辑后的文档而不重命名它。所以标准保存,而不是另存为。
处理这个问题的最佳方法是什么?
我想将一个NSTextView
对象添加到我的应用程序中,并添加一个操作来打开位于 textView 中的应用程序包中的 .txt 文件。另外 - 我希望可以选择编辑和保存编辑后的文档而不重命名它。所以标准保存,而不是另存为。
处理这个问题的最佳方法是什么?
使用 NSString 加载文件并将其放在您的文本视图中:
NSTextView *textView; //your NSTextView object
NSError *err = nil;
NSString *path = [[NSBundle mainBundle] pathForResource:@"EditableFile" ofType:@"txt"];
NSString *contents = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&err];
if(!contents) {
//handle error
}
[textView setString:contents];
储蓄正好相反。获取字符串并将其写入文件:
NSTextView *textView; //your NSTextView object
NSError *err = nil;
NSString *path = [[NSBundle mainBundle] pathForResource:@"EditableFile" ofType:@"txt"];
NSString *contents = [textView string];
if(![contents writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&err]) {
//handle error
}