通过表名获取列名,封装数据[FMResultSet]
手机终端开发中,经常会遇到和后台进行大量数据交互的情况,通常情况是json串或者xml串,通常这种key-value形式的数据怎样封装对应到数据表对应的对象呢?
FMDataBase中FMResultSet提供了一个实例方法:
- (void)setupColumnNames {
if (!columnNameToIndexMap) {
[self setColumnNameToIndexMap:[NSMutableDictionary dictionary]];
}
int columnCount = sqlite3_column_count(statement.statement);
int columnIdx = 0;
for (columnIdx = 0; columnIdx < columnCount; columnIdx++) {
[columnNameToIndexMap setObject:[NSNumber numberWithInt:columnIdx]
forKey:[[NSString stringWithUTF8String:sqlite3_column_name(statement.statement, columnIdx)] lowercaseString]];
}
columnNamesSetup = YES;
}
在这个方法中,对数据库表的列名建立了索引,即可以通过表名,来获取一个FMResultSet对象,进而来建立列名的所以,从而获取到列。
以下是我一个封装的方法:
//根据表名封装数据
- (NSString *) packingSyncDataByTableName:(NSString *) tableName
{
NSString *theSql=[NSString stringWithFormat:PACKING_DATA_SQL,tableName];
packedSyncData = [[@"\"" stringByAppendingString:tableName] stringByAppendingString:@"\":"];
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
FMDatabase *database = [[appDelegate fmdb] retain];
FMResultSet *resultSet=[database executeQuery:theSql];
[resultSet setupColumnNames];
// [resultSet resultDict];
NSEnumerator *columnNames = [resultSet.columnNameToIndexMap keyEnumerator];
NSString *tempColumnName= nil;
NSMutableArray *columnNameArray = [[[NSMutableArray alloc] init] autorelease];
while ((tempColumnName = [columnNames nextObject]))
{
[columnNameArray addObject:tempColumnName];
}
NSMutableArray *syncArray = [[[NSMutableArray alloc] init] autorelease];
NSString *columnName = nil;
while ([resultSet next])
{
NSMutableDictionary *syncData = [[[NSMutableDictionary alloc] init] autorelease];
for(int i =0;i<columnNameArray.count;i++)
{
columnName = [columnNameArray objectAtIndex:i];
NSString *columnValue = [resultSet stringForColumn: columnName];
if (columnValue==nil) {
columnValue=@"";
}
[syncData setObject:columnValue forKey:columnName];
}
[syncArray addObject:syncData];
}
if ([syncArray count]==0) {
return nil;
}
packedSyncData =[packedSyncData stringByAppendingString:[syncArray JSONRepresentation]];
NSLog(@"The packed sync Data is:%@",packedSyncData);
return packedSyncData;
}