您的位置:首页 > 移动开发 > Objective-C

利用object-c反射功能封装FMDB

2012-04-23 23:22 155 查看
http://hi.baidu.com/%CA%FD%D1%A7rubish/blog/item/fabea81efe7dae7cf724e4ea.html

在利用fmdb操作sqllite的时候,感觉存在很多冗余代码,所以偶发其想,想到了java的反射,java的很多orm框架都利用了反射这一高级语言的功能,我只能说很好很强大
coredata没见过源码,我感觉或多或少应该也是应用的反射功能
google了一些资料,决定封装一个保存功能,此处暂提供一个思路,具体还需要修改优化
代码如下:
-(void)saveEntity:(Entity *)entity{



Class class = [entity class];



unsigned int outCount;



objc_property_t *properties = class_copyPropertyList(class,&outCount);



NSString *sql = [NSString stringWithFormat:@" INSERT INTO %@ (",[entity tableName]];



NSString *sqlValue = @" VALUES (";



NSMutableArray *dic = [[NSMutableArray alloc] initWithCapacity:5];



for(int i = 0 ; i<outCount ; i++){



const char *pName = property_getName(properties[i]);



NSString *propertyName = [NSString stringWithCString:pName encoding:NSUTF8StringEncoding];



NSObject *value = [entity valueForKey:propertyName];



if(value != nil){

[dic addObject:value];

}



if(i == outCount - 1){

sql = [sql stringByAppendingString:propertyName];

sqlValue = [sqlValue stringByAppendingString:@"?"];

//sqlValue = [sqlValue stringByAppendingFormat:@"%@",value];

}else {

sql = [sql stringByAppendingString:propertyName];

sqlValue = [sqlValue stringByAppendingString:@"?"];

//sqlValue = [sqlValue stringByAppendingFormat:@"%@",value];

sql = [sql stringByAppendingString:@","];

sqlValue = [sqlValue stringByAppendingString:@","];

}



}



sql = [sql stringByAppendingString:@")"];

sqlValue = [sqlValue stringByAppendingString:@")"];

free(properties);



NSLog(@"%@",[NSString stringWithFormat:@"%@%@",sql,sqlValue]);



SqliteInterface *interface = [SqliteInterface sharedSqliteInterface];



FMDatabase *db = [interface connectDB];



[db beginTransaction];

[db executeUpdate:[NSString stringWithFormat:@"%@%@",sql,sqlValue]withArgumentsInArray:dic];

[db commit];



[interface closeDB];





}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐