在制作DEMO中,使用到了获取程序文件路径的自定义方法:
-(NSString*)documentsDirectory{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
return documentsDirectory;
}
其中,NSDocumentDirectory 是指程序中对应的Documents路径,而NSDocumentionDirectory对应于程序中的Library/Documentation路径,这个路径是没有读写权限的,所以看不到文件生成。
iOS中NSSearchPathForDirectoriesInDomains函数
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory
, NSUserDomainMask
, YES);
NSLog(@"Get document path: %@",[paths objectAtIndex:0]);NSString *fileName=[[paths objectAtIndex:0] stringByAppendingPathComponent:@"myFile"];
NSString *content=@"write data into myFile";
NSData *contentData=[content dataUsingEncoding:NSASCIIStringEncoding];
if ([contentData writeToFile:fileName atomically:YES]) {
NSLog(@">>write ok.");
}NSString *contentChinese=@"写入汉字信息到文件";
NSData *contentChineseData=[contentChinese dataUsingEncoding:NSUnicodeStringEncoding];
if ([contentData writeToFile:fileName atomically:YES]) {
NSLog(@">>写入成功。");