2015-11-03 42 views
0

当我使用模拟器,我可以找到数据库文件/文件。但是当我用我的iPhone运行项目如何使用iOS的sqlite的,我无法找到数据库文件。 什么时候应该创建数据库文件或在我的项目中使用此代码?当我使用iPhone运行项目

NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentFolderPath = [searchPaths objectAtIndex:0]; 
NSString *dbFilePath = [documentFolderPath stringByAppendingString:DATABASENAME]; 
NSFileManager *fm = [NSFileManager defaultManager]; 
BOOL isExist = [fm fileExistsAtPath:dbFilePath]; 
if (!isExist) { 
    NSString *backupDbPath = [[[NSBundle mainBundle]resourcePath]stringByAppendingString:DATABASENAME]; 
    [fm copyItemAtPath:backupDbPath toPath:dbFilePath error:nil]; 
} 
+0

尝试此链接http://stackoverflow.com/questions/24826352/why-a-database-hasnt-created/24826701#24826701 – karthikeyan

+0

它不工作.....当我创建模拟器和iPhone之间有什么区别一个数据库文件? – rayesquire

回答

0

第一次或数据库文件中的文件目录不存在,你必须复制数据库文件到文件目录:

-(void)copyDatabaseIntoDocumentsDirectory{ 
    // Check if the database file exists in the documents directory. 
    NSString *destinationPath = [self.documentsDirectory stringByAppendingPathComponent:self.databaseFilename]; 
    if (![[NSFileManager defaultManager] fileExistsAtPath:destinationPath]) { 
     // The database file does not exist in the documents directory, so copy it from the main bundle now. 
     NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:self.databaseFilename]; 
     NSError *error; 
     [[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:destinationPath error:&error]; 

     // Check if any error occurred during copying and display it. 
     if (error != nil) { 
      NSLog(@"%@", [error localizedDescription]); 
     } 
    } 
} 

编号:http://www.appcoda.com/sqlite-database-ios-app-tutorial/

0

你可以用” t访问iPhone或iPad的目录。所以即使你成功创建了一个数据库,你也不会看到它。你可以通过读取数据来判断它的存在。

相关问题