2012-03-27 26 views
0

我遇到以下代码加载SQLite数据库的问题。Sqlite数据库加载失败 - 问题与SQLite准备语句 - iPhone - xCode 4.3.1

- (NSArray *)getDatabase { 

NSLog(@"Get Database Called"); 

    NSMutableArray *retval = [[[NSMutableArray alloc] init] autorelease]; 
    NSString *query = @"SELECT Description, UniqueID, HexCoords, NoHexCoords, NoAnnots, AnnotText, DescriptionFormatting, HexCoordsPortrait FROM MainTable"; 
    sqlite3_stmt *statement; 
    if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, nil) 
     == SQLITE_OK) { 
     while (sqlite3_step(statement) == SQLITE_ROW) { 

      char *nameChars = (char *) sqlite3_column_text(statement, 0); 
      char *desChars = (char *) sqlite3_column_text(statement, 1); 
      int uniqueID = sqlite3_column_int(statement, 2); 

从使用断点,我可以看到的问题是与if语句和代码永远不会越过这个if语句。任何人都可以发现什么可能是错的?代码在几个月前工作,我最近升级到xCode 4.3,所以这可能是问题吗?

提前致谢。

+0

唯一的原因,我可以看到这样的表现是,如果_database没有正确设置。也许打电话来打开数据库?另外,最后一个参数应该是'NULL',而不是'nil',因为参数不是指向对象的指针。目前都编译为0,所以不应该导致问题,但我不知道他们会保持相同的任何保证。 – 2012-03-27 10:36:34

回答

1

是的,我同意约阿希姆。有时候DB有没有真正连接的问题。我做的是几件事情。首先我在应用程序代理中添加以下代码。

- (void) copyDatabaseIfNeeded { 

    //Using NSFileManager we can perform many file system operations. 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSError *error; 
    NSString *dbPath = [self getDBPath]; 
    BOOL success = [fileManager fileExistsAtPath:dbPath]; 

    if(success) { 

     NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"MyDB.sqlite"]; 
     success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error]; 

     if (!success) 
      NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]); 
    } 
} 

在ApplicationDidFinishLaunching中调用此函数。

现在删除当前在你的包中的数据库。 (请确保你有它的备份)。并且(如果可能,从Iphone Simulator文件夹中删除所有项目)Coz有时会附加上一个数据库。 清理您的项目,在ur包中添加数据库。编译..

让我知道,如果它的工作

的获取通道功能

- (NSString *) getDBPath { 
     //Search for standard documents using NSSearchPathForDirectoriesInDomains 
     //First Param = Searching the documents directory 
     //Second Param = Searching the Users directory and not the System 
     //Expand any tildes and identify home directories. 
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES); 
     NSString *documentsDir = [paths objectAtIndex:0]; 
     return [documentsDir stringByAppendingPathComponent:@"MYDB.sqlite"]; 
} 
+0

谢谢 - 但什么是“getDBPath”的方法? – GuybrushThreepwood 2012-03-27 11:00:16

+0

对不起忘了提到 – WaaleedKhan 2012-03-27 11:18:45

+0

还有一件事我想补充..在函数u张贴在你的问题你设置返回类型为(NSArray *)它不是最好的做法..你应该使用NSMutableArray – WaaleedKhan 2012-03-27 11:29:40