0

我在 iPhone 设备上使用 NSFileManager 创建目录和文件时遇到问题。我的代码如下所示,在模拟器上运行良好,但在设备上运行良好,您能帮帮我吗?给我一些可能的问题的方向,谢谢你的每一个回复..

我首先以这种方式创建目录:

NSFileManager *fileMgr = [NSFileManager defaultManager];
NSArray *arPaths = NSSearchPathForDirectoriesInDomains(NSDownloadsDirectory, NSUserDomainMask, YES);
NSString *appPath = [[NSString alloc] init];
appPath = [arPaths objectAtIndex:0];

strDownloadsDir = [[NSString alloc] init];
strDownloadsDir = [[appPath stringByAppendingPathComponent:@"/Other"] copy];
if(![fileMgr fileExistsAtPath:strDownloadsDir])
    [fileMgr createDirectoryAtPath:strDownloadsDir attributes:nil];

然后我尝试以这种方式在此目录中创建新文件:

NSString *filePath = [strDownloadsDir stringByAppendingPathComponent:strDlFileName];
//Test whether this file exists, if not, create it
NSLog(@"%@", filePath);
if(![fileMgr fileExistsAtPath:filePath])
{
    if([fileMgr createFileAtPath:filePath contents:nil attributes:nil])
        NSLog(@"Creating new file at path %@", filePath);
    else
        NSLog(@"Failed to create new file.");
}

整个 NSFileManager 似乎有问题,因为当我使用 fileExistAtPath 时,它给出的路径是

NSArray *arPaths = NSSearchPathForDirectoriesInDomains(NSDownloadsDirectory, NSUserDomainMask, YES);
NSString *appPath = [[NSString alloc] init];
appPath = [arPaths objectAtIndex:0];

它也不起作用,我试图将目录更改为 NSDocumentsDirectory 但它没有帮助

4

3 回答 3

1

可能是因为苹果不推荐使用“createDirectoryAtPath:attrubutes:”方法.....

于 2010-01-11T10:28:23.917 回答
0

您只能在应用程序的沙箱目录下创建文件。Apple 不允许您从中创建文件。

这就是你手机失败的原因吗?

于 2010-06-29T09:11:58.923 回答
0
[[NSFileManager defaultManager] createDirectoryAtPath:strPath withIntermediateDirectories:YES attributes:nil error:nil];

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *strFile = [documentsDirectory stringByAppendingPathComponent:@"hello/config.plist"];
        NSLog(@"strFile: %@", strFile);

        NSString *strPath = [documentsDirectory stringByAppendingPathComponent:@"hello"];
        if (![[NSFileManager defaultManager] fileExistsAtPath:strPath]) {
            NSLog(@"there is no Directory: %@",strPath);
            [[NSFileManager defaultManager] createDirectoryAtPath:strPath withIntermediateDirectories:YES attributes:nil error:nil];
        }

        NSArray *keys = [NSArray arrayWithObjects: @"username", @"password", @"serverName", @"serverPort", @"autoSave", nil];
        NSArray *values = [NSArray arrayWithObjects: @"11", @"11", @"11", @"11", @"11", nil];

        NSDictionary *configInfo = [[NSDictionary alloc] initWithObjects: values forKeys:keys];
        if (![configInfo writeToFile: strFile atomically: YES]) {
            NSLog(@"write file error");
        }
于 2011-04-15T03:19:11.997 回答