我现在正在学习如何在 ios 中创建和管理文件和文件夹。但我似乎不能正确地做文件夹部分。我下面的代码有什么问题?
- (void)viewDidLoad
{
[super viewDidLoad];
NSFileManager *filemgr;
NSString *dataFile;
NSString *docsDir;
NSString *newDir;
NSArray *dirPaths;
BOOL isDir;
filemgr = [NSFileManager defaultManager];
// Identify the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
// Build the path to the data file
if ([filemgr fileExistsAtPath:@"newfolder" isDirectory:&isDir] && isDir) {
NSLog(@"folder already created!");
}else{
NSLog(@"create new folder now...");
newDir = [docsDir stringByAppendingPathComponent:@"newfolder"];
}
dataFile = [docsDir stringByAppendingPathComponent:
@"/newfolder/datafile.dat"];
// Check if the file already exists
if ([filemgr fileExistsAtPath: dataFile])
{
// Read file contents and display in textBox
NSData *databuffer;
databuffer = [filemgr contentsAtPath: dataFile];
NSString *datastring = [[NSString alloc]
initWithData: databuffer
encoding:NSASCIIStringEncoding];
_textBox.text = datastring;
}
}
- (IBAction)saveText:(id)sender {
NSFileManager *filemgr;
NSData *databuffer;
NSString *dataFile;
NSString *docsDir;
NSArray *dirPaths;
filemgr = [NSFileManager defaultManager];
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
dataFile = [docsDir
stringByAppendingPathComponent: @"/newfolder/datafile.dat"];
databuffer = [_textBox.text
dataUsingEncoding: NSASCIIStringEncoding];
[filemgr createFileAtPath: dataFile
contents: databuffer attributes:nil];
}
我不确定会发生什么,但每次我运行模拟时,它都会给我一个空白文本字段,尽管我之前已经输入了一些文本。我按照这里的教程和谷歌搜索了目录创建部分的其他示例。好像出了什么问题??谢谢!