3

我正在尝试在我的应用程序库目录中的子目录中创建文件。首先,我得到这样的图书馆路径:

- (NSURL*) getLibraryDirectory
{
    NSFileManager* manager = [NSFileManager defaultManager];
    NSArray* paths = [manager URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask];

    if ([paths count] > 0)
    {
        return [paths objectAtIndex:0];
    }
    return nil;
}

然后我使用以下代码创建子文件夹:

- (NSURL*) getDirectory:(NSString*)subdirName
{
    NSFileManager* sharedFM = [NSFileManager defaultManager];
    NSURL* libraryDirectory = [self getLibraryDirectory];

    if (libraryDirectory)
    {
        NSURL* subdir = [libraryDirectory URLByAppendingPathComponent:subdirName isDirectory:YES];
        if (![sharedFM fileExistsAtPath:[subdir absoluteString] isDirectory:YES])
        {
            NSError* error;
            if ([sharedFM createDirectoryAtURL:subdir withIntermediateDirectories:YES attributes:nil error:&error])
            {
                return subdir;
            } 
            else 
            {
                NSLog(@"Error occured while trying to create subdirectory \"%@\". Code - %d, desc - %@", subdirName, [error code], [error localizedDescription]);
            }
        }
    }
    return nil;
}

最后一件事我试图在这个文件夹中创建一些文件,如下所示:

NSString* filePath = [[self getDirectory:DIR_COMMANDS] absoluteString];
if (filePath)
{
    filePath = [filePath stringByAppendingPathComponent:@"test_file.tst"];       

    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager createFileAtPath:filePath contents:[[NSData alloc] initWithBytes:[[@"string" dataUsingEncoding:NSUTF16LittleEndianStringEncoding] bytes] length:12] attributes:nil])
    {
        NSLog(@"YES");
    }
    else
    {
        NSLog(@"NO");
    }
}

但不幸的是,我每次都得到“不”,不明白为什么。

4

1 回答 1

6

要从文件 URL 获取路径,您必须使用path而不是absoluteString.

NSString *filePath = [[self getDirectory:DIR_COMMANDS] path];

旁注:您应该采用 Cocoa 的方法命名风格:libraryDirectory而不是getLibraryDirectory,甚至更好:libraryDirectoryURL。仅当get通过引用传递返回值时才使用前缀。

另外:您的用法fileExistsAtPath:isDirectory:不正确。BOOL参数通过引用传递:

BOOL isDir;
if ([sharedFM fileExistsAtPath:[subdir path] isDirectory:&isDir]) {
    if (! isDir) {
        NSLog(@"There's a plain file at my path");
        return nil;
    }
}
于 2013-02-28T18:07:58.453 回答