沒(méi)寫(xiě)完待續(xù)...
//
// myModle.m
// 字典轉(zhuǎn)模型-runtime,kvc
//
// Created by yaning Zhu on 16/8/31.
// Copyright ? 2016年 yaning Zhu. All rights reserved.
//
#import "myModle.h"
#import <objc/runtime.h>
@implementation myModle
//1 手動(dòng)解析,就是每個(gè)屬性按順序賦值,笨重切費(fèi)時(shí)
/*2 KVC ...簡(jiǎn)單介紹一下KVC,就是key value Codeing的意思,翻譯一下就是鍵值編碼,蘋(píng)果官方為我們能用到的包括NSObject NSArray等常見(jiàn)的類(lèi)都做了一個(gè)叫NSKeyValueCoding的分類(lèi),而KVC的操作方法由NSKeyValueCoding協(xié)議提供,也就是說(shuō)我們用到的Objc都是支持KVC的.
再說(shuō)一下KVC的作用,主要目的就是給對(duì)象賦值和取值,當(dāng)然不單單是給你能看得到的屬性,iOS在編譯階段會(huì)將一個(gè)類(lèi)的屬性及其對(duì)應(yīng)的值都放進(jìn)內(nèi)存,可以通過(guò)runtime獲得到,具體方法下面已經(jīng)提供,所以KVC能解決官方?jīng)]有提供接口的某些屬性的值,例如UISwitch的顏色等.
3 小馬哥的MJExtension JsonModel等三方
*/
- (instancetype)initWithDic:(NSDictionary *)dic
{
self = [super init];
if (self) {
//利用KVC解析
[self setValuesForKeysWithDictionary:dic];
}
return self;
}
- (instancetype)init
{
self = [super init];
if (self) {
NSDictionary * dic = [self getAllPropertiesAndVaules];
NSLog(@"%@",dic);
NSArray * arr = [self getAllProperties];
NSLog(@"%@",arr);
[self getAllMethods];
}
return self;
}
/* 獲取對(duì)象的所有屬性和屬性?xún)?nèi)容 */
- (NSDictionary *)getAllPropertiesAndVaules
{
NSMutableDictionary *props = [NSMutableDictionary dictionary];
unsigned int outCount, i;
objc_property_t *properties =class_copyPropertyList([UISwitch class], &outCount);
for (i = 0; i<outCount; i++)
{
objc_property_t property = properties[i];
const char* char_f =property_getName(property);
NSString *propertyName = [NSString stringWithUTF8String:char_f];
id propertyValue = [[UISwitch new] valueForKey:(NSString *)propertyName];
if (propertyValue) [props setObject:propertyValue forKey:propertyName];
}
free(properties);
return props;
}
/* 獲取對(duì)象的所有屬性 */
- (NSArray *)getAllProperties
{
u_int count;
objc_property_t *properties =class_copyPropertyList([UISearchBar class], &count);
NSMutableArray *propertiesArray = [NSMutableArray arrayWithCapacity:count];
for (int i = 0; i < count ; i++)
{
const char* propertyName =property_getName(properties[i]);
[propertiesArray addObject: [NSString stringWithUTF8String: propertyName]];
}
free(properties);
return propertiesArray;
}
/* 獲取對(duì)象的所有方法 */
-(void)getAllMethods
{
unsigned int mothCout_f =0;
Method* mothList_f = class_copyMethodList([self class],&mothCout_f);
for(int i=0;i<mothCout_f;i++)
{
Method temp_f = mothList_f[i];
IMP imp_f = method_getImplementation(temp_f);
SEL name_f = method_getName(temp_f);
const char* name_s =sel_getName(method_getName(temp_f));
int arguments = method_getNumberOfArguments(temp_f);
const char* encoding =method_getTypeEncoding(temp_f);
NSLog(@"方法名:%@,參數(shù)個(gè)數(shù):%d,編碼方式:%@",[NSString stringWithUTF8String:name_s],
arguments,
[NSString stringWithUTF8String:encoding]);
}
free(mothList_f);
}
@end
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者