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

在利用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];
     
    
}



from: http://hi.baidu.com/suncgsamsom/item/3908ae5a6ac34ccad3e10ca6

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值