Mac OS 沙盒下创建自有文件以及读写(不使用用户权限,不使用NSSavePanel和NSOpenPanel)

  最近做的一个应用要用到临时读写文件,又不能使用用户权限或者NSSavePanel、NSOpenPanel,经过尝试,选择了在Containers中保存文件。在这里,用一个小Demo做演示。

首先给window拖一个textview,拖两个button,分别设置title为Save和Read。

在AppDelegate.m中创建一个内部类,定义一个插座变量textView

1 @interface AppDelegate()
2 @property (unsafe_unretained) IBOutlet NSTextView *textView;
3 @end

 设置一个获取路径的方法,在此方法中,如果文件存在返回路径,如果文件不存在则创建一个文件。

1 - (NSString *)filePath{
2     NSArray *appDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSAllDomainsMask, YES);
3     NSString *path =  [appDirectory.firstObject stringByAppendingString:@"/Untitle.onecodego"];
4     if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
5         [[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil];
6     }
7     NSLog(@"%@",path);
8     return path;
9 }

创建两个IBAction,并关联到对应的button上

1 - (IBAction)saveButtonAction:(NSButton *)sender {
2     [self.textView.textStorage.string writeToFile:[self filePath] atomically:YES encoding:NSUTF8StringEncoding error:nil];
3 }
4 - (IBAction)readButtonAction:(NSButton *)sender {
5     NSData *data = [NSData dataWithContentsOfFile:[self filePath]];
6     NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
7     [self.textView.textStorage setAttributedString:[[NSAttributedString alloc] initWithString:str]];
8 }

此时点击Save会将textView中的字符串保存到本地: /Users/onecodego/Library/Containers/com.onecodego.myTest/Data/Documents/Untitle.onecodego 。

点击Read会将本地文件中保存的数据读取出来显示到textView

 

posted on 2014-04-24 16:48  onecodego  阅读(2321)  评论(0)    收藏  举报

导航