使用NSTextView对象打开/编辑位于应用程序包中的.txt文件

Pau*_*aul 4 cocoa nstextview

我想NSTextView在我的应用程序中添加一个对象,并添加一个操作,打开位于textView中应用程序包中的.txt文件.另外 - 我希望可以选择编辑和保存已编辑的文档而无需重命名.所以标准保存,不保存为.

处理这个问题的最佳方法是什么?

ugh*_*fhw 13

使用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];
Run Code Online (Sandbox Code Playgroud)

拯救恰恰相反.获取字符串并将其写入文件:

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
}
Run Code Online (Sandbox Code Playgroud)