0

我正在 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 中,这样我就可以在任何其他内存被弄乱之前将其作为第一件事运行。(这应该出现在所有观点之前,如果我对此是正确的。)但我不知道问题出在哪里。再次,注释掉两行中的任何一条,上面写着“Correct when”会产生预期的结果。或者用SELECT *而不是查询SELECT id, type, state也将产生所需的结果。

4

1 回答 1

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;
}
于 2012-08-28T07:40:18.260 回答