美文网首页
runtime绑定属性方法字典转模型

runtime绑定属性方法字典转模型

作者: 那个谁_5207 | 来源:发表于2017-06-12 15:22 被阅读28次

    runtime动态绑定属性  

    首先创建一个分类以NSString为例

    在NSString+apping.h  中加入了一个number属性

    @interface NSString (apping)

    @property(nonatomic, assign) NSInteger number;

    @end

    NSString+apping.m中  用关键字@dynamic修饰number属性  @dynamic的作用苹果文档翻译后的意思大概是:您可以使用@ dynamic关键字告诉编译器,您将通过直接或在运行时使用其他机制(例如动态加载代码或动态方法解析)来实现由属性所隐含的API契约。它抑制了如果编译器无法找到合适的实现,则会生成的警告。您应该只使用它,如果您知道方法将在运行时可用。 因为是动态绑定需要导入objc/runtime头文件,具体实现如下

    #import <objc/runtime.h>

    @dynamic number;

    static char stringNumber;

    - (void)setNumber:(NSInteger)number{

    objc_setAssociatedObject(self, &stringNumber, [NSString stringWithFormat:@"%ld",number], OBJC_ASSOCIATION_COPY);

    }

    - (NSInteger)number{

    return [objc_getAssociatedObject(self, &stringNumber) integerValue];

    }


    runtime实现字典转模型

    创建名为person的Model类添加字典转换方法

    Person.h

    @interface Person : NSObject

    @property(nonatomic, copy)NSString *name;

    @property(nonatomic, copy)NSString *phone;

    @property(nonatomic, assign)NSInteger sex;

    @property(nonatomic, copy)NSString *age;

    + (instancetype)modelWithDic:(NSDictionary*)dic;


    Person.m

    #import <objc/runtime.h>

    //字典转模型


    + (instancetype)modelWithDic:(NSDictionary*)dic{

    id objc = [[self alloc] init];

    unsigned int count = 0;

    Ivar *ivarList = class_copyIvarList(self, &count);

    for (int i = 0; i < count; i ++) {

    Ivar ivar = ivarList[i];

    NSString *ivarName = [NSString stringWithUTF8String:ivar_getName(ivar)];

    NSString *key = [ivarName substringFromIndex:1];

    id value = dic[key];

    if (value) {

    [objc setValue:value forKey:key];

    }

    }

    return objc;

    }

    runtime动态修改属性值

    在ViewController.m中导入Person  创建一个person属性

    @interface ViewController ()

    @property(nonatomic, strong)Person *person;

    @end

    @implementation ViewController

    - (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    _person = [Person modelWithDic:@{@"name":@"niyuanbo", @"phone":@"18883278185", @"sex":@1, @"age":@"33"}];

    [self change];

    //打印出的age为30

    NSLog(@"%@, %@  %ld %@", _person.name, _person.phone,_person.sex,_person.age);



    }

    - (void)change{

    unsigned int count = 0;

    Ivar *ivar = class_copyIvarList([self.person class], &count);

    for (int i = 0; i < count; i ++) {

    Ivar var = ivar[i];

    const char *varname = ivar_getName(var);

    NSString *name = [NSString stringWithUTF8String:varname];

    if ([name isEqualToString:@"_age"]) {

    object_setIvar(self.person, var, @"30");

    break;

    }

    }

    }

    相关文章

      网友评论

          本文标题:runtime绑定属性方法字典转模型

          本文链接:https://www.haomeiwen.com/subject/roelqxtx.html