【问题标题】:SQLite Problem - Database pathSQLite 问题 - 数据库路径
【发布时间】:2010-07-19 14:11:39
【问题描述】:

我正在尝试从数据库中选择数据,并且我有以下代码: 代码:

// Setup the database object
 sqlite3 *database;

 // Init the animals Array
 list = [[NSMutableArray alloc] init];
 NSLog(@"documents path: ", documentsDir); 
 NSLog(@"database path: ", databasePath);

 // Open the database from the users filessytem
 if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) 
 {
  // Setup the SQL Statement and compile it for faster access
  const char *sqlStatement = "select route_name from Route";
  sqlite3_stmt *compiledStatement;
  if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) 
  {
   // Loop through the results and add them to the feeds array
   while(sqlite3_step(compiledStatement) == SQLITE_ROW) 
   {
    // Read the data from the result row
    NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];

    // Add the animal object to the animals Array
    //[list addObject:animal];    
    [list addObject:aName];    
    //[animal release];
   }
  }
  // Release the compiled statement from memory
  sqlite3_finalize(compiledStatement);  
 }
 sqlite3_close(database);

我在第一个 IF 语句中收到 EXC_BAD_ACCESS 错误。大家有什么想法。

同样在 NSLOG 文档中,Dir 和 databasePath 都是空白的。

我在 ViewDidLoad 中有以下代码:

-(void)viewDidLoad 
{ 
 // Setup some globals
 databaseName = @"xxxxxxCoreData.sqlite";

 // Get the path to the documents directory and append the databaseName
 NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *documentsDir = [documentPaths objectAtIndex:0];
 documentsDir = [documentPaths objectAtIndex:0];
 databasePath = [documentsDir stringByAppendingPathComponent:databaseName];

【问题讨论】:

  • 发布NSLog("%@", databasePath);的输出
  • 看来documentsDir有问题,这里发生EXC_BAD_ACCESS错误,控制台什么也没有显示。
  • 我稍微修改了代码,现在我得到了数据库路径,但它不会通过以下 IF 语句: if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)

标签: iphone sqlite


【解决方案1】:

看起来 databasePath 没有保留,所以在视图加载和数据库代码运行之间,它已经被释放了。如果要保留这些变量,则需要将最后两行更改为:

documentsDir = [[documentPaths objectAtIndex:0] retain];
databasePath = [[documentsDir stringByAppendingPathComponent:databaseName] retain];

既然您在viewDidLoad 中执行此操作,您应该在viewDidUnload(在此方法中也设置为nil)和dealloc 中释放它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    • 2013-04-14
    • 1970-01-01
    • 1970-01-01
    • 2013-05-06
    • 2015-10-15
    • 1970-01-01
    相关资源
    最近更新 更多