可能由于内存损坏而可能涉及FMDB的崩溃

时间:2012-07-24 01:36:31

标签: objective-c fmdb

我正在iOS模拟器上进行测试,该模拟器涉及与MapBox iOS SDK一起分发的FMDB。这是一个我无法捕捉的错误,我想知道我是否违反了一些我不知道的FMDB规则,或者我在某处遇到严重的内存损坏(但我已经将问题缩小到几行)。以下代码将在注释“不应该在这里”的行中运行。并且注释掉下面标记的任何行都会遇到“应该在这里”。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    NSString * sql_gdb = @"/Users/t2wu/Library/Application Support/iPhone Simulator/5.1/Applications/BB193B94-2549-49DB-9BBB-C66D76743515/Library/Application Support/Poki.OfflineSpotty/fremont_spatial.gdb";

    FMDatabase * db = [FMDatabase databaseWithPath:sql_gdb];
    if ([db open]) {
        db.shouldCacheStatements = TRUE; // Correct when this line is commented out

        [self fooDB:db];

        FMResultSet * debug1 = [db executeQuery:@"SELECT id, type, state FROM payloads WHERE id=?", [NSNumber numberWithLong:2]];
        BOOL DOESFIND1 = FALSE;
        while ([debug1 next]) {
            DOESFIND1 = TRUE;
            NSLog(@"Does find."); // Should be here.
        }
        if (DOESFIND1 == FALSE) {
            NSLog(@"Does not find"); // Should not be here.
        }
    }

    return YES;
}

-(void) fooDB: (FMDatabase *)db
{
    NSLog(@"SELECT id, type, state FROM payloads WHERE id=%@", [NSNumber numberWithLong:1]);
    FMResultSet * result = [db executeQuery:@"SELECT id, type, state FROM payloads WHERE id=?", [NSNumber numberWithLong:1]];   // Correct when changed to "SELECT * FROM"  
    while ([result next]) {
        return;  // Correct when this line is commented out.
    }
    return;
}

我已将代码放在application:didFinishLaunchingWithOptions中,因此我可以在任何其他内存被搞乱之前将其作为第一件事运行。 (这应该在所有观点之前,如果我对此是正确的。)但我不知道问题出在哪里。再次,注释出“正确何时”将产生预期结果的两行中的任何一行。或者使用SELECT *而不是SELECT id, type, state进行查询也会产生所需的结果。

1 个答案:

答案 0 :(得分:0)

我想评论您编写数据库代码和方法的方式,fooDB有点难以阅读。

尝试以下方法:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
 [self fooDB];
 return YES;
}

-(BOOL) fooDB
{

   NSString * sql_gdb = @"/Users/t2wu/Library/Application Support/iPhone Simulator/5.1/Applications/BB193B94-2549-49DB-9BBB-C66D76743515/Library/Application Support/Poki.OfflineSpotty/fremont_spatial.gdb";

   FMDatabase * db = [FMDatabase databaseWithPath:sql_gdb];
   if (![db open]) {
      NSLog(@"Could not open DB.");
      return NO;
   }    

   FMResultSet * result = [db executeQuery:@"SELECT id, type, state FROM payloads WHERE id = ?", [NSNumber numberWithLong:1]];   
  while ([result next]) {
      //DO SOMETHING HERE
  }
  [result close];
  [db close];
  return YES;
}