Mojo-database是我我的比較喜歡多開源項目,下文是該項目打介紹和地址:
mojo-database
簡介:
MojoDatabase is an ActiveRecord-like ORM for SQLite written in Objective-C for use in iOS applications.git
The goal is to provide a nicer user interface for using SQLite with Objective-C applications via the ActiveRecord pattern.github
下面,我將介紹一下mojo的對象映射機制。下面的代碼就是model執行findsql是運
行的代碼sql
NSArray *results = [database executeSql:sql withParameters:parameters withClassForRow:[self class]];
從代碼的[self class]就是把本身的類傳遞過去,app
withParameters:(NSArray *)parameters withClassForRow:(Class )rowClass
在execute函數中,有以下代碼。ide
if (needsToFetchColumnTypesAndNames) { columnTypes = [self columnTypesForStatement:statement]; columnNames = [self columnNamesForStatement:statement]; needsToFetchColumnTypesAndNames = NO; } id row = [[rowClass alloc] init]; [self copyValuesFromStatement:statement toRow:row queryInfo:queryInfo columnTypes:columnTypes columnNames:columnNames]; [rows addObject:row]; }
其中id row = [[rowClass alloc] init];
動態建立對象了,其中sqlite支持的類型有函數
-(int)columnTypeToInt:(NSString *)columnType { if ([columnType isEqualToString:@"INTEGER"]) { return SQLITE_INTEGER; } else if ([columnType isEqualToString:@"REAL"]) { return SQLITE_FLOAT; } else if ([columnType isEqualToString:@"TEXT"]) { return SQLITE_TEXT; } else if ([columnType isEqualToString:@"BLOB"]) { return SQLITE_BLOB; } else if ([columnType isEqualToString:@"NULL"]) { return SQLITE_NULL; } return SQLITE_TEXT; }
提取數值的代碼this
-(id)valueFromStatement:(sqlite3_stmt *)statement column:(int)column queryInfo:(NSDictionary *)queryInfo columnTypes:(NSArray *)columnTypes { int columnType = [[columnTypes objectAtIndex:column] intValue]; /* * force conversion to the declared type using sql conversions; this saves * some problems with NSNull being assigned to non-object values */ if (columnType == SQLITE_INTEGER) { return [NSNumber numberWithInt:sqlite3_column_int(statement, column)]; } else if (columnType == SQLITE_FLOAT) { return [NSNumber numberWithDouble:sqlite3_column_double(statement, column)]; } else if (columnType == SQLITE_TEXT) { const char* text = (const char *) sqlite3_column_text(statement, column); if (text != nil) { return [NSString stringWithUTF8String:text]; } else { return @""; } } else if (columnType == SQLITE_BLOB) { // create an NSData object with the same size as the blob return [NSData dataWithBytes:sqlite3_column_blob(statement, column) length:sqlite3_column_bytes(statement, column)]; } else if (columnType == SQLITE_NULL) { return nil; } NSLog(@"Unrecognized SQL column type: %i for sql %@", columnType, [queryInfo objectForKey:@"sql"]); return nil; }
設置對象屬性的代碼code
[row setValue:value forKey:[columnNames objectAtIndex:i]]; }