今天調試BUG,發現幾個問題都是對FMDB誤用引起的,解決後記錄一下:
先是通過resultDictionary方法,將ResultSet轉換成NSDictionary
FMResultSet *rs = [db executeQuery:sql]; while ([rs next]) { [result addObject:[rs resultDictionary]]; }
NSString* originFilePath = [row objectForKey:columnName];// 原始文件路徑 if (originFilePath){ // 非空處理 }
NSString* originFilePath = [row objectForKey:columnName];// 原始文件路徑 if ((NSNull *)originFilePath != [NSNull null]){ // 非空處理 }
做一個簡單的全表查詢,返回結果居然是0 row,最後發現表名不能是變量,以下2種寫法都是錯的
FMResultSet *rs = [db executeQuery:@"select * from %@", tableName];
FMResultSet *rs = [db executeQuery:@"select * from ?", tableName];
NSString *sql = [NSString stringWithFormat:@"select * from %@", tableName]; FMResultSet *rs = [db executeQuery:sql];
執行一句SQL時,FMDB報EXC_BAD_ACCESS,應用崩潰。在stackoverflow上查到,傳給execute方法的參數,必須是NSObject。如果本來是原始數據類型如int,long等,要先用Wrapper類包裝一下。以下的代碼是錯的:
FMResultSet *rs = [db executeQuery:sql, latestBackupTime, now];// latestBackupTime和now是long類型,造成EXC_BAD_ACCESS
long now = [[NSDate date] timeIntervalSince1970]; // 傳給executeQuery()的參數必須是NSObject,不能是原始數據類型,否則報EXC_BAD_ACCESS FMResultSet *rs = [db executeQuery:sql, [NSNumber numberWithLong:latestBackupTime], [NSNumber numberWithLong:now]];