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

来源:互联网 发布:老滚5捏脸数据 编辑:程序博客网 时间:2024/05/21 10:43

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];
     
    
}


原创粉丝点击