成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

iOS手動打造JSON Model轉換庫

移動開發 iOS
前一段時間學習了Runtime,對類和對象的結構,和一些消息轉發有一些自己的理解,現在希望簡單的應用下,就決定自己寫一個簡單的JSON與Model的相互轉化,現在總結下。

 觀察下面這個JSON數據和Model數據

  1. NSString *girlFriend = @"白菜";  
  2. id parmenters = @{  
  3.         @"girlFriend":girlFriend,  
  4.         @"age":@22.1,  
  5.         @"name":@"Lastdays",  
  6.         @"time":@"2016-03-18 5:55:49 +0000"  
  7. }; 
  1. @interfaceModel: NSObject  
  2.    
  3. @property NSNumber *age;  
  4. @property NSString *name;  
  5. @property NSString *girlFriend;  
  6. @property NSData *time;  
  7.    
  8. @end 

開始的時候仔細想了一下,如何能夠動態的去添加屬性值,并且根據對應的屬性進行賦值,還要保證類型正確,這是我最開始考慮的問題。但是最核心問題就是 動態實現 。

我們一步一步來解決問題,首先我們先獲取Model屬性,取得Model的一些信息
獲取Model屬性

runtime提供了 class_copyPropertyList 來獲取屬性列表,OK,我們可以來看一下用它獲取的數據是什么樣的?查看runtime源碼

  1. /***********************************************************************  
  2. * class_copyPropertyList. Returns a heap block containing the  
  3. * properties declared in the class, or nil if the class  
  4. * declares no properties. Caller must free the block.  
  5. * Does not copy any superclass's properties.  
  6. **********************************************************************/  
  7. objc_property_t*class_copyPropertyList(Class cls, unsigned int *outCount)  
  8. {  
  9.     old_property_list*plist;  
  10.     uintptr_titerator = 0;  
  11.     old_property**result = nil;  
  12.     unsigned int count = 0;  
  13.     unsigned int p, i;  
  14.    
  15.     if (!cls) {  
  16.         if (outCount) *outCount = 0;  
  17.         return nil;  
  18.     }  
  19.    
  20.     mutex_locker_tlock(classLock);  
  21.    
  22.     iterator = 0;  
  23.     while ((plist = nextPropertyList(cls, &iterator))) {  
  24.         count += plist->count;  
  25.     }  
  26.    
  27.     if (count > 0) {  
  28.         result = (old_property**)malloc((count+1) * sizeof(old_property*));  
  29.    
  30.         p = 0;  
  31.         iterator = 0;  
  32.         while ((plist = nextPropertyList(cls, &iterator))) {  
  33.             for (i = 0; i < plist->count; i++) {  
  34.                 result[p++] = property_list_nth(plist, i);  
  35.             }  
  36.         }  
  37.         result[p] = nil;  
  38.     }  
  39.    
  40.     if (outCount) *outCount = count;  
  41.     return (objc_property_t*)result;  
  1. typedef struct old_property*objc_property_t; 
  1. struct old_property {  
  2.     const char *name;  
  3.     const char *attributes;  
  4. }; 

從上面的三段runtime源碼中,課本上就能判斷出,其實返回結果就是一些old_property,并且每個old_property中含有對應的name和其他信息。

總結起來說就是**class_copyPropertyList**獲取Model屬性列表,屬性列表里面的objc_property_t包含著這個屬性的類型和名字等一些信息。

根據剛才的分析設計出以下結構:

  1. bash  
  2. -(id)modelToJsonObject:(NSObject *)model{  
  3.    
  4.     Class cls = self.class;  
  5.     unsigned int countProperty = 0;  
  6.     objc_property_t*propertys = class_copyPropertyList(cls,&countProperty);  
  7.     NSMutableDictionary *dic = [NSMutableDictionary new];  
  8.    
  9.     for (unsigned int i = 0; i<countProperty; i++) {  
  10.         PropertyInfo *propertyInfo = [[PropertyInfo alloc]initWithProperty:propertys[i]];  
  11.         if (propertyInfo.propertyName!=nil) {  
  12.             dic[propertyInfo.propertyName] = [selfLYModelSetJsonObjectWith:modelpropertyInfo:propertyInfo];  
  13.         }  
  14.     }  
  15.     return dic;  

PropertyInfo也就是屬性信息,我們將Model的所有屬性存放到 NSMutableDictionary 中,key就是屬性名,Value就是PropertyInfo。

接下來開始獲取Model的屬性信息 PropertyInfo

我們可以通過property_getName來獲取屬性名

  1. const char *property_getName(objc_property_tprop)  
  2. {  
  3.     return oldproperty(prop)->name;  

接下來就是獲取屬性的類型和一些其他的信息。獲取屬性的信息其實和上面的原理差不多,我們使用property_copyAttributeList,

  1. objc_property_attribute_t*property_copyAttributeList(objc_property_tprop,   
  2.                                                       unsigned int *outCount)  
  3. {  
  4.     if (!prop) {  
  5.         if (outCount) *outCount = 0;  
  6.         return nil;  
  7.     }  
  8.    
  9.     mutex_locker_tlock(classLock);  
  10.     return copyPropertyAttributeList(oldproperty(prop)->attributes,outCount);  

看到這里,不往下繼續分析源碼了,其實可以看到,attributes就是我們想要的信息,其實每個property也是有自己對應的attributes。

這個attributes是什么樣呢?翻看源碼,找到了答案

  1. typedef struct {  
  2.     const char *name;        
  3.     const char *value;          
  4. } objc_property_attribute_t; 

加一下斷點,看看

可以看到,name是T,Value是NSNumber,我們來獲取下NSNumber這個屬性類型。

  1. for (unsigned int i = 0; i<attrCount; i++) {  
  2.     if (attrs[i].name[0] == 'T') {  
  3.         size_tlen = strlen(attrs[i].value);  
  4.         if (len>3) {  
  5.             char name[len - 2];  
  6.             name[len - 3] = '';  
  7.             memcpy(name, attrs[i].value + 2, len - 3);  
  8.             _typeClass = objc_getClass(name);  
  9.         }  
  10.     }  

基本上我們想要的信息基本上都已經獲取到了,現在接下來就是做動態設定。

中間做個插曲簡單的說下Objc是動態語言,[receiver message]的執行過程當中,[receiver message]是會被動態編譯的,Objc是動態語言,因此它會想盡辦法將編譯連接推遲到運行時來做。runtime這個時實運行系統就是來執行編譯后的代碼。

在這個消息發送過程中,objc_msgSend充當著很重要的角色,所以我們可以主動觸發objc_msgSend,來模擬getter,setter方法獲取屬性值,或者建立。

我們通過SEL來定義選擇器,選擇器是什么?就是方法名的唯一標識符

根據剛才的想法,編寫的代碼***是這個樣子

  1. -(instancetype)initWithProperty:(objc_property_t)property{  
  2.     _property = property;  
  3.    
  4.     const char *name = property_getName(property);  
  5.     if (name) {  
  6.         _propertyName = [NSStringstringWithUTF8String:name];  
  7.     }  
  8.     unsigned int attrCount;  
  9.     objc_property_attribute_t*attrs = property_copyAttributeList(property, &attrCount);  
  10.     for (unsigned int i = 0; i<attrCount; i++) {  
  11.         if (attrs[i].name[0] == 'T') {  
  12.             size_tlen = strlen(attrs[i].value);  
  13.             if (len>3) {  
  14.                 char name[len - 2];  
  15.                 name[len - 3] = '';  
  16.                 memcpy(name, attrs[i].value + 2, len - 3);  
  17.                 _typeClass = objc_getClass(name);  
  18.             }  
  19.         }  
  20.     }  
  21.     NSString *setter = [NSStringstringWithFormat:@"set%@%@:", [_propertyNamesubstringToIndex:1].uppercaseString, [_propertyNamesubstringFromIndex:1]];  
  22.     _setter =  NSSelectorFromString(setter);  
  23.     _getter = NSSelectorFromString(_propertyName);  
  24.    
  25.     return self;  

基本的準備工作,和一些問題都解決了,接下來可以寫功能了。
JSON轉Model

根據剛才說的,我們可以主動觸發objc_msgSend,來模擬setter方法建立屬性值。設計出以下方法

  1. -(void)LYModelSetPropertyWithModel:(id) modelvalue:(id)valuepropertyInfo:(PropertyInfo *) propertyInfo{  
  2.     ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, propertyInfo.setter, value);  

我們將Model的所有屬性存放到 NSMutableDictionary 中,key就是屬性名,Value就是PropertyInfo。

現在就可以動態設定了

  1. -(BOOL)LYModelSelectProperties:(NSDictionary *)dictonary{  
  2.    
  3.     ClassInfo *cls = [[ClassInfo alloc]initWithClass:object_getClass(self)];  
  4.     id key, value;  
  5.     NSArray *keys = [dictonaryallKeys];  
  6.     NSUInteger count = [keyscount];  
  7.     for (int i = 0; i < count; i++){  
  8.         key = [keysobjectAtIndex: i];  
  9.         value = [dictonaryobjectForKey: key];  
  10.    
  11.         if (cls.propertyInfo[key]) {  
  12.             [selfLYModelSetPropertyWithModel:selfvalue:valuepropertyInfo:cls.propertyInfo[key]];  
  13.         }  
  14.     }  
  15.     return YES;  

完成動態設定
Model轉JSON

原理跟JSON轉Model

我們可以主動觸發objc_msgSend,來模擬getter方法來獲取屬性值。

  1. -(id)LYModelSetJsonObjectWith:(id)modelpropertyInfo:(PropertyInfo *)propertyInfo{  
  2.     id value = ((id (*)(id, SEL))(void *) objc_msgSend)((id)model, propertyInfo.getter);  
  3.     return value;  

建立NSDictionary

  1. -(id)modelToJsonObject:(NSObject *)model{  
  2.    
  3.     Class cls = self.class;  
  4.     unsigned int countProperty = 0;  
  5.     objc_property_t*propertys = class_copyPropertyList(cls,&countProperty);  
  6.     NSMutableDictionary *dic = [NSMutableDictionary new];  
  7.    
  8.     for (unsigned int i = 0; i<countProperty; i++) {  
  9.         PropertyInfo *propertyInfo = [[PropertyInfo alloc]initWithProperty:propertys[i]];  
  10.         if (propertyInfo.propertyName!=nil) {  
  11.             dic[propertyInfo.propertyName] = [selfLYModelSetJsonWith:modelpropertyInfo:propertyInfo];  
  12.         }  
  13.     }  
  14.     return dic;  

完成獲取
測試

  1. NSString *girlFriend = @"白菜";  
  2.     id parmenters = @{  
  3.                       @"girlFriend":girlFriend,  
  4.                       @"age":@22.1,  
  5.                       @"name":@"Lastdays",  
  6.                       @"time":@"2016-03-18 5:55:49 +0000"  
  7.                       };  
  8.    
  9.     Model *model = [ModelLYModelWithJSON:parmenters];  
  10.     NSLog(@"%@",model.girlFriend);  
  11.     NSLog(@"%@",model.name);  
  12.     NSLog(@"%@",model.age);  
  13.     NSLog(@"%@",model.time);  
  14.    
  15.     NSLog(@"========================================");  
  16.    
  17.     NSDictionary *jsonObject= [modelLYModelToJson];  
  18.     NSLog(@"%@",jsonObject); 

結果:

總結

簡單的JSON Model轉換庫,關鍵點就是在于對runtime的理解。就當自己的一個小練習,后續會繼續維護,讓它對更多類型進行支持。代碼結構上可能不是那么好,后續會將整體的結構重新設計下,增加可讀性,也歡迎來提出建議。

責任編輯:陳琳 來源: 伯樂在線
相關推薦

2016-11-29 10:20:50

SwiftJSONModel工具庫

2015-10-28 09:55:39

Swift解析生產庫

2011-04-22 13:44:34

JacksonJSON

2010-06-30 11:16:50

SQL Server

2014-07-17 10:06:02

Model-View-iOS App

2009-06-15 15:10:02

Java數據轉換JSON

2022-10-13 21:07:48

數據庫SQL Server

2015-08-07 09:33:24

RuntimeModel

2009-08-13 09:33:07

JavaBean到XM

2010-01-05 14:49:03

JSON格式

2015-11-24 09:53:22

AngularJSXMLJSON

2021-05-27 10:02:57

Go緩存數據

2010-01-08 10:49:21

JSON 轉換工具

2020-10-22 08:01:52

XMLJSON轉換

2021-01-04 05:40:58

MySQL數據庫

2020-06-10 14:16:57

iOS 13.6 be蘋果更新

2024-03-12 09:10:21

GoarenaAPI

2015-08-10 10:04:28

2013-07-25 14:44:48

sqlite實例教程iOS開發學習sqlite打造詞典

2011-10-14 09:36:20

DNA數據庫
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 国产精品欧美大片 | 久久精品二区 | 欧美成人免费在线 | 成人精品一区二区三区 | 久久9久 | 午夜av在线 | 免费毛片网 | 国产精品无 | 搞av.com| 亚洲一区| 午夜影院中文字幕 | 免费精品| 国产成人99久久亚洲综合精品 | av网站观看 | 免费一二区 | 亚洲v日韩v综合v精品v | 亚洲欧美在线一区 | 久久av资源网 | 日本精品一区二区三区在线观看 | 国产精品久久久久一区二区三区 | 日本a∨视频 | 国产精品久久久久久久久久不蜜臀 | 亚洲成人在线视频播放 | 精品国产不卡一区二区三区 | 国产第一亚洲 | 亚洲精品日韩精品 | 在线欧美一区 | 黑人巨大精品欧美黑白配亚洲 | 一级毛片免费 | 在线免费看91 | 天天干天天玩天天操 | 欧美日韩电影一区二区 | 精品中文字幕一区二区 | 亚洲香蕉在线视频 | 日韩网 | 日韩一区二区不卡 | 国产精品久久久久无码av | 日韩免费高清视频 | 久久国产精品一区二区 | 黄色免费av | 国产a区 |