createFileAtPath:contents:attributes:给出“没有这样的文件或目录”错误

时间:2013-01-22 05:40:44

标签: iphone ios objective-c nsfilemanager

我正在尝试编写一个简单的createDB函数。如果DB文件不存在,我想创建它并继续。但是在尝试创建文件时,我收到“No Such file or directory”错误。

以下是代码段:

-(void) createDB
{
    NSString* docsDir;
    NSArray* dirPaths;

    // Get directory path
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);    
    docsDir = [dirPaths objectAtIndex:0];
    dbPath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:@"players.db"]];
    NSFileManager* fileMgr = [NSFileManager defaultManager];


    if([fileMgr fileExistsAtPath:dbPath] == NO)
    {
        //Create the file in main application folder
        //dbPath = [[NSBundle mainBundle] pathForResource:@"players" ofType:@".db"];

        if (![fileMgr createFileAtPath:dbPath contents:nil attributes:nil])
            NSLog(@"Error was code: %d - message: %s", errno, strerror(errno));
        // Above NSLog Prints : Error was code: 2 - message: No such file or directory

        NSLog(@"DB PAth : %@",dbPath);
        //Prints "DB Path : /Users/myname/Library/Application Support/iPhone Simulator/6.0/Applications/016E0BD6-E615-4031-A9E4-42E42D863ECB/Library/Documentation/"


        if(sqlite3_open_v2([dbPath UTF8String], &playerDB, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, NULL) == SQLITE_OK)
        {
            char* errorMsg;
            const char* sql_stmt = "CREATE TABLE IF NOT EXISTS PLAYERS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, GAME TEXT, GAME_DESC TEXT, DOB TEXT, IMAGE BLOB);";
            if (sqlite3_exec(playerDB, sql_stmt, nil, nil, &errorMsg) != SQLITE_OK)
            {
                NSLog(@"%s Create Table '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(playerDB), sqlite3_errcode(playerDB));
            }
        }
        else
            NSLog(@"%s Open DB '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(playerDB), sqlite3_errcode(playerDB));
    }
}

如果有人有任何意见,请告诉我。

2 个答案:

答案 0 :(得分:0)

将<{1}}替换为

NSDocumentationDirectory'

我认为应该是

NSDocumentDirectory

答案 1 :(得分:0)

我认为这一行存在问题:

NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);

应该是:

NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  

<强> NSDocumentationDirectory

Documentation.

Available in iOS 2.0 and later.

Declared in NSPathUtilities.h.
     

<强> NSDocumentDirectory

Document directory.

Available in iOS 2.0 and later.

Declared in NSPathUtilities.h.

查看NSSearchPathDirectory了解详情。