Mojo-database是我个人比较喜欢多开源项目,下文是该项目打介绍和地址:
mojo-database
简介:
MojoDatabase is an ActiveRecord-like ORM for SQLite written in Objective-C for use in iOS applications.
The goal is to provide a nicer user interface for using SQLite with Objective-C applications via the ActiveRecord pattern.
下面,我将介绍一下mojo的对象映射机制。下面的代码就是model执行findsql是运
行的代码
NSArray *results = [database executeSql:sql
withParameters:parameters withClassForRow:[self class]];
从代码的[self class]就是把自己的类传递过去,
withParameters:(NSArray *)parameters
withClassForRow:(Class )rowClass
在execute函数中,有如下代码。
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;
}
提取数值的代码
-(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;
}
设置对象属性的代码
[row setValue:value forKey:[columnNames objectAtIndex:i]];
}
时间: 2024-11-05 02:32:56