0

我现在正在学习如何在 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];
}

我不确定会发生什么,但每次我运行模拟时,它都会给我一个空白文本字段,尽管我之前已经输入了一些文本。我按照这里的教程和谷歌搜索了目录创建部分的其他示例。好像出了什么问题??谢谢!

4

2 回答 2

2

问题出在这一行:

if ([filemgr fileExistsAtPath:@"newfolder" isDirectory:&isDir] && isDir) {
    NSLog(@"folder already created!"); 

您需要将完整路径作为fileExistsAtPathLike 的参数传递:

NSSTring *folderPath = [docsDir stringByAppendingPathComponent:
            @"newfolder"];
if ([filemgr fileExistsAtPath:folderPath isDirectory:&isDir] && isDir) {
        NSLog(@"folder already created!"); 
于 2013-06-10T03:50:13.260 回答
0

以下是更新的工作版本,以防有人在寻找它:

newDir = [docsDir stringByAppendingPathComponent:@"newfolder"];
    if ([filemgr fileExistsAtPath:newDir isDirectory:&isDir] && isDir) {
        NSLog(@"folder already created!");
    }else{
        NSLog(@"create new folder now...");
        [filemgr createDirectoryAtPath:newDir withIntermediateDirectories:YES
                            attributes:nil error: NULL];

    }
于 2013-06-10T04:22:37.963 回答