iphone - 在 iPhone 的 Library 目录中创建文件

标签 iphone ios nsfilemanager

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

- (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");
    }
}

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

最佳答案

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

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

旁注:您应该采用 Cocoa 的方法命名风格:libraryDirectory 而不是 getLibraryDirectory,或者更好:libraryDirectoryURLget 前缀仅在返回值通过引用传递时使用。

另外:您对 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;
    }
}

关于iphone - 在 iPhone 的 Library 目录中创建文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15142447/

相关文章:

iphone - iOS 瓶颈 : Global variable vs. 核心数据或属性列表

android - native 应用程序 android 和 ios 上的文本转语音

iphone - 在 iPhone 中创建一个目录

iphone - iOS:从磁盘读取时如何获得透明的png

iPhone + 轻微内存泄漏 + 应用程序崩溃

ios - Swift 3 UITableViewDataSource 选择器

ios - 如何仅在选择休息选项卡栏项目上显示选项卡栏项目的标题,在 Swift 中将没有标题

ios - .DS_Store 文件跳过

swift - 使用 swift 在沙盒 Mac 应用程序中访问文件

iphone - 未使用自定义键盘调用 UItextView 委托(delegate)