在开发中,有时测试的时候不能链接在电脑上,所以需要做一个Log持久化,此文仅为记录我遇到的坑。
- (void)fileManager {
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
//创建一个文件用于写数据(第一次是必要的)
if (![[NSFileManager defaultManager] fileExistsAtPath:[path stringByAppendingString:@"/testout.txt"]]) {
[[NSFileManager defaultManager] createFileAtPath:[path stringByAppendingString:@"/testout.txt"] contents:nil attributes:nil];
NSLog(@"creat");
}
[@"txt12345" writeToFile:[path stringByAppendingString:@"/testout.txt"] atomically:NO encoding:NSUTF8StringEncoding error:nil];
//验证文件的内容是否写入
NSLog(@"%@",[NSString stringWithContentsOfFile:[path stringByAppendingString:@"/testout.txt"] encoding:NSUTF8StringEncoding error:nil]);
}
//NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"tmp"];//temp文件夹
复制代码
其中,NSDocumentDirectory 是指程序中对应的Documents路径,而NSDocumentationDirectory对应于程序中的Library/Documentation路径,这个路径是没有读写权限的,所以看不到文件生成。