zoukankan      html  css  js  c++  java
  • 一行代码实现FMDB的CURD操作

    上次实现FMDB的CURD基本操作后,用在项目里,每个实体类都要写SQL语句来实现创建表和CURD操作,总觉得太麻烦,然后就想着利用反射和kvc来实现一个数据库操作的基类继承一下,子类只需要继承,然后添加自己的属性就好,这里做一个总结。

    第一个难点:获取子类的所有属性以及类型

    OC中有提供获取所有property的方法,需要用到objc_property_t和class_copyPropertyList。

    objc_property_t *properties =class_copyPropertyList([selfclass], &outCount); 数组properties有所有的属性以及其相应的属性类型。具体的代码如下:

    /**
     *  获取该类的所有属性
     */
    + (NSDictionary *)getPropertys
    {
        NSMutableArray *proNames = [NSMutableArray array];
        NSMutableArray *proTypes = [NSMutableArray array];
        NSArray *theTransients = [[self class] transients];
        unsigned int outCount, i;
        objc_property_t *properties = class_copyPropertyList([self class], &outCount);
        for (i = 0; i < outCount; i++) {
            objc_property_t property = properties[i];
            //获取属性名
            NSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
            if ([theTransients containsObject:propertyName]) {
                continue;
            }
            [proNames addObject:propertyName];
            //获取属性类型等参数
            NSString *propertyType = [NSString stringWithCString: property_getAttributes(property) encoding:NSUTF8StringEncoding];
            /*
             c char         C unsigned char
             i int          I unsigned int
             l long         L unsigned long
             s short        S unsigned short
             d double       D unsigned double
             f float        F unsigned float
             q long long    Q unsigned long long
             B BOOL
             @ 对象类型 //指针 对象类型 如NSString 是@“NSString”
             
             
             64位下long 和long long 都是Tq
             SQLite 默认支持五种数据类型TEXT、INTEGER、REAL、BLOB、NULL
             */
            if ([propertyType hasPrefix:@"T@"]) {
                [proTypes addObject:SQLTEXT];
            } else if ([propertyType hasPrefix:@"Ti"]||[propertyType hasPrefix:@"TI"]||[propertyType hasPrefix:@"Ts"]||[propertyType hasPrefix:@"TS"]||[propertyType hasPrefix:@"TB"]) {
                [proTypes addObject:SQLINTEGER];
            } else {
                [proTypes addObject:SQLREAL];
            }
            
        }
        free(properties);
        
        return [NSDictionary dictionaryWithObjectsAndKeys:proNames,@"name",proTypes,@"type",nil];
    }
    propertyTpe 在Xcode document 中,截图


    类型主要是在创建表的时候需要用到,SQLite只支持五种数据类型TEXTINTEGERREALBLOBNULL,这里就需要将获取到得属性的类型转换一下,我主要用了TEXT/INTEGER/REAL三种。

    然后就是拼接SQL语句了,这个也比较简单,创建表的SQL语句拼接在这里:

    + (NSString *)getColumeAndTypeString
    {
        NSMutableString* pars = [NSMutableString string];
        NSDictionary *dict = [self.class getAllProperties];
        
        NSMutableArray *proNames = [dict objectForKey:@"name"];
        NSMutableArray *proTypes = [dict objectForKey:@"type"];
        
        for (int i=0; i< proNames.count; i++) {
            [pars appendFormat:@"%@ %@",[proNames objectAtIndex:i],[proTypes objectAtIndex:i]];
            if(i+1 != proNames.count)
            {
                [pars appendString:@","];
            }
        }
        return pars;
    }
    第二个难点:查询出来的数据赋值给对象的对应属性

    这里用到了KVC来赋值,主要方法就是setValue:forKey:

    依然是先判断属性的类型,然后转换相应的数据类型,我这里主要是NSString和NSNumber。

    if ([columeType isEqualToString:SQLTEXT]) {
                        [model setValue:[resultSet stringForColumn:columeName] forKey:columeName];
                    } else {
                        [model setValue:[NSNumber numberWithLongLong:[resultSet longLongIntForColumn:columeName]] forKey:columeName];
                    }

    第三个难点:子类在实例化时,直接创建对应的数据库表,这里用dispatch_once实现,只需要创建一次。子类中覆写createTable方法。

    + (BOOL)createTable
    {
        __block BOOL result = YES;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            result = [super createTable];
        });
        return result;
    }
    因为会有多线程操作,所以用单例和FMDatabaseQueue来执行,要避免queue里调用queue执行操作。

    有一些属性不需要与数据库表字段映射,覆写方法+ (NSArray *)transients;在改方法中返回不需要映射的字段数组。

    基类中的方法如下:

    /** 
     *  获取该类的所有属性
     */
    + (NSDictionary *)getPropertys;
    
    /** 获取所有属性,包括主键 */
    + (NSDictionary *)getAllProperties;
    
    /** 数据库中是否存在表 */
    + (BOOL)isExistInTable;
    
    /** 保存或更新
     * 如果不存在主键,保存,
     * 有主键,则更新
     */
    - (BOOL)saveOrUpdate;
    /** 保存单个数据 */
    - (BOOL)save;
    /** 批量保存数据 */
    + (BOOL)saveObjects:(NSArray *)array;
    /** 更新单个数据 */
    - (BOOL)update;
    /** 批量更新数据*/
    + (BOOL)updateObjects:(NSArray *)array;
    /** 删除单个数据 */
    - (BOOL)deleteObject;
    /** 批量删除数据 */
    + (BOOL)deleteObjects:(NSArray *)array;
    /** 通过条件删除数据 */
    + (BOOL)deleteObjectsByCriteria:(NSString *)criteria;
    
    /** 查询全部数据 */
    + (NSArray *)findAll;
    
    /** 通过主键查询 */
    + (instancetype)findByPK:(int)inPk;
    
    /** 查找某条数据 */
    + (instancetype)findFirstByCriteria:(NSString *)criteria;
    
    /** 通过条件查找数据 
     * 这样可以进行分页查询 @" WHERE pk > 5 limit 10"
     */
    + (NSArray *)findByCriteria:(NSString *)criteria;
    
    #pragma mark - must be override method
    /**
     * 创建表
     * 如果已经创建,返回YES
     */
    + (BOOL)createTable;
    /** 如果子类中有一些property不需要创建数据库字段,那么这个方法必须在子类中重写 
     */
    + (NSArray *)transients;

    JKDBModel添加了自动更新的检测和添加实体类字段的功能。最新代码在Github。

    具体用法请转到github下载源码:https://github.com/Joker-King/JKDBModel


  • 相关阅读:
    mysql小数和类型转换函数
    concat()用法
    sql修改表名字段名
    having函数,case when与order by
    volatile实现原理与应用
    synchronized的实现原理与应用
    java8策略模式
    centos7快速升级gcc
    一个用户从发起请求到接收到响应,中间经过哪些服务,每个服务做什么事情
    Java注解
  • 原文地址:https://www.cnblogs.com/wanghang/p/6298869.html
Copyright © 2011-2022 走看看