29

好的,

所以我有一个需要更新的 Cydia 应用程序。我知道 Cydia 应用程序没有 Documents 文件夹,因此您必须创建一个。这是我之前在 iOS 4 中的制作方法(在 iOS 5 上不起作用):

mkdir("/var/mobile/Library/APPNAME", 0755);
mkdir("/var/mobile/Library/APPNAME/Documents", 0755);

NSString *foofile = @"/var/mobile/Library/APPNAME/Documents/database.db";
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];

if (fileExists == TRUE) {
    NSLog(@"already exists");
} else {
    NSLog(@"doesn't exists");
    NSFileManager *fileManager = [[NSFileManager defaultManager]autorelease];
    NSError *error;
    NSString *documentDBFolderPath = @"/var/mobile/Library/APPNAME/Documents/database.db";

    NSString *resourceDBFolderPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"database.db"];
    [fileManager copyItemAtPath:resourceDBFolderPath toPath:documentDBFolderPath error:&error];

}

我还包含了将数据库文件复制到该文件夹​​的代码。这不起作用(即使我通过 SSH 手动创建文件夹)。

请帮忙!谢谢。

4

5 回答 5

63

这是我创建目录的方法

-(void)createDirectory:(NSString *)directoryName atFilePath:(NSString *)filePath
{
    NSString *filePathAndDirectory = [filePath stringByAppendingPathComponent:directoryName];
    NSError *error;

    if (![[NSFileManager defaultManager] createDirectoryAtPath:filePathAndDirectory
                                   withIntermediateDirectories:NO
                                                    attributes:nil
                                                         error:&error])
    {
        NSLog(@"Create directory error: %@", error);
    }
}
于 2011-11-06T20:38:28.230 回答
5

尝试使用createDirectoryAtURL:withIntermediateDirectories:attributes:error:.

NSFileManager类参考

createDirectoryAtURL:withIntermediateDirectories:attributes:error:

在指定路径创建具有给定属性的目录。

参数

url- 指定要创建的目录的文件 URL。如果要指定相对路径,则必须在创建对应的 NSURL 对象之前设置当前工作目录。此参数不得为 nil。

createIntermediates- 如果YES是,此方法创建任何不存在的父目录作为在 url 中创建目录的一部分。如果NO,如果任何中间父目录不存在,此方法将失败。如果任何中间路径元素对应于文件而不是目录,则此方法也会失败。

attributes- 新目录和任何新创建的中间目录的文件属性。您可以设置所有者和组编号、文件权限和修改日期。如果您为此参数指定 nil 或省略特定值,则会使用一个或多个默认值,如讨论中所述。有关可以包含在此字典中的键列表,请参阅“常量”(第 54 页)部分列出了在属性字典中用作键的全局常量。某些键,例如 NSFileHFSCreatorCode 和 NSFileHFSTypeCode,不适用于目录。

error- 在输入时,指向错误对象的指针。如果发生错误,则将此指针设置为包含错误信息的实际错误对象。如果您不想要错误信息,您可以为此参数指定 nil。


YES如果目录已创建或已经存在,则返回值;如果发生错误,则返回 NO。

于 2011-11-06T20:30:12.767 回答
3

检查NSFileManager 的类参考。要创建您需要的文件夹createDirectoryAtPath:withIntermediateDirectories:attributes:error:

于 2011-11-06T20:20:36.737 回答
1

iOS5文件系统的精湛技术解释

于 2013-03-22T01:04:57.613 回答
1

在 Swift 中,如果存在或创建,则返回 true。

func ensureDirectoryExists(path:String) -> Bool {

    if !NSFileManager.defaultManager().fileExistsAtPath(path) {
        do {
            try NSFileManager.defaultManager().createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil)
        } catch {
            print(error)
            return false
        }
    }
    return true
}
于 2016-07-18T21:20:35.840 回答