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


  • 相关阅读:
    了解jQuery
    了解JavaScript
    了解DOM
    了解CSS
    UICollectionViewCell点击高亮效果(附带效果GIF)
    产品迭代缓慢的原因
    了解Web的相关知识
    HTML常用标签
    HTML常用标签效果展示
    了解数据产品经理
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/5194642.html
Copyright © 2011-2022 走看看