本地?cái)?shù)據(jù)庫(kù)文件轉(zhuǎn) model

發(fā)現(xiàn)公司的項(xiàng)目中的數(shù)據(jù)不是從網(wǎng)絡(luò)獲取,而是一個(gè)創(chuàng)建好的.db文件,其中有很多表,就寫(xiě)了個(gè)轉(zhuǎn) model 的方法

創(chuàng)建單例,以便整個(gè)項(xiàng)目任何地方使用

  • 代碼
    // .h 文件中的代碼
    
    #import "DataBase.h"
    
    static DataBase *_DBCtl = nil;

    @interface DataBase(){
    
        FMDatabase  *_db;
    }
    
    @end
    
    
    
    @implementation DataBase

        #pragma mark - 初始化數(shù)據(jù)庫(kù)
        
        //創(chuàng)建數(shù)據(jù)庫(kù),并將數(shù)據(jù)庫(kù)轉(zhuǎn)成 model 存在數(shù)組中方便全局使用
        
        - (void)creatDataBase {
        
            NSString *filePath = [[NSBundle mainBundle] pathForResource:@"DLDT" ofType:@"db"];
        
            if(!_db){
                _db = [FMDatabase databaseWithPath:filePath];
            }      
        }
        
        
        /**
        將數(shù)據(jù)庫(kù)轉(zhuǎn)成model
        @param table 數(shù)據(jù)庫(kù)中表的名字
        @param myClass model , 存儲(chǔ)屬性名對(duì)應(yīng)數(shù)據(jù)庫(kù)中的字段名
        @return 裝有model的數(shù)組
        */
    
        - (NSMutableArray *)getTable:(NSString *)table fromClass:(NSObject *)myClass {
    
            if (![_db open]) {  return nil; }
            
            //數(shù)據(jù)庫(kù)數(shù)組
            NSMutableArray *arrSQL = [[NSMutableArray alloc] init];
            
            // 查詢(xún)數(shù)據(jù)庫(kù)
            NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@",table];
            
            FMResultSet *res = [_db executeQuery:sql];
            
            // 定義一個(gè)變量記錄對(duì)應(yīng) model 的屬性數(shù)量和屬性名集合
            unsigned int outCount;
            
            while ([res next]) {
            
                // 獲取傳入類(lèi)的屬性名
                objc_property_t *propertys = class_copyPropertyList([myClass class], &outCount);
                
                // 創(chuàng)建一個(gè)字典,用來(lái)存儲(chǔ)數(shù)據(jù)庫(kù)的 K-V
                NSMutableDictionary *dicProperty = [NSMutableDictionary dictionary];
                
                for (int i = 0; i < outCount; i ++) {
                
                    //獲取屬性名
                    objc_property_t property = propertys[i];  
                    
                    // 將屬性名作為字典 key
                    NSString *strKey = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
                    
                    // 用 key 去是數(shù)據(jù)庫(kù)中獲取值
                    NSString *strValue = [res stringForColumn:strKey];
                    
                    // 去空
                    strValue = strValue == nil ? @"" : strValue;
                    
                    [dicProperty setObject:strValue forKey:strKey];    //存值
                }
                
                // 釋放屬性
                free(propertys);
                
                // 轉(zhuǎn) model
                myClass = [[myClass class] mj_objectWithKeyValues:dicProperty];
                
                // 放入數(shù)組
                [arrSQL addObject:myClass];
            }
            
            [_db close]; // 關(guān)閉數(shù)據(jù)庫(kù)
            
            return arrSQL;  // 返回裝有 model 的數(shù)組
        }
    
    @end
    

使用

  • 代碼
    //這是 .m 文件中的實(shí)現(xiàn),用tableView 展示數(shù)據(jù)庫(kù)美容

    
    - (void)viewDidLoad {
    
        [super viewDidLoad];
        
        self.title = @"數(shù)據(jù)庫(kù)轉(zhuǎn)model";
        _arrInfo = [[DataBase shareData] getTable:@"station" fromClass:[DataModel copy]];
    }
    
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
        NSString *cellID = @"station";
        
        DataModelCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        
        if (!cell) {
        
            cell = [[DataModelCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        _model = _arrInfo[indexPath.row];
            
        cell.label.text = _model.StationName;
        
        return cell;
    
    }
    
    
    //下面是 swift 版 
    
    // 只要將 db 文件的引入,傳入相應(yīng)表名和  model 類(lèi),就可以得到相應(yīng)model 了,
    
    //將數(shù)據(jù)庫(kù)轉(zhuǎn)成 model
    
    private func getTable(table : String , from className : NSObject.Type) -> (NSMutableArray) {
        
        if db?.open() == false { return [] }
             
        let MyClass : NSObject.Type? = className
    
        let arrSQL = NSMutableArray()
        let path = "SELECT * FROM \(table)"
        let result = db?.executeQuery(path, withArgumentsIn: nil)
        var outCount : UInt32 = 0
    
        while (result?.next())! {
    
            let properties  = class_copyPropertyList(MyClass, &outCount)
    
            let dic = NSMutableDictionary()  
             
            for index in 0 ..< numericCast(outCount) {
    
                let property : objc_property_t = properties![index]!
    
                let key : String = NSString.init(utf8String: property_getName(property)) as! String
    
                let value = result?.string(forColumn: key)
    
                //存字典
                dic.setObject(value ?? "", forKey: key as NSCopying)
            }
        
        
            free(properties)
        
            var myClass = MyClass?.init()
            myClass =  MyClass!.mj_object(withKeyValues: dic)
            arrSQL.add(myClass!)
        }
    
        return arrSQL
    }

效果
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容