runtime——归档

#import <Foundation/Foundation.h>

 

@interface PYPeople : NSObject

@property (nonatomic, assign) int age;

@property (nonatomic, assign) int height;

@property (nonatomic, copy) NSString *name;

@property (nonatomic, assign) int age2;

@property (nonatomic, assign) int height2;

@property (nonatomic, assign) int age3;

@property (nonatomic, assign) int height3;

@property (nonatomic, assign) int age4;

@property (nonatomic, assign) int height4;

@end

 

#import "PYPeople.h"

#import <objc/runtime.h>

@implementation PYPeople

-(void)encodeWithCoder:(NSCoder *)encoder{

    

    unsigned int count = 0;

    Ivar *ivars = class_copyIvarList([PYPeople class], &count);

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

       Ivar ivar = ivars[i];

        const char*name =ivar_getName(ivar);

        NSString *key =[NSString  stringWithUTF8String:name];

        id value =[self  valueForKey:key];

        [encoder  encodeObject:value forKey:key];

        

    }

    free(ivars);

    

}

-(id)initWithCoder:(NSCoder *)decoder

{

    if (self= [super init]) {

        unsigned int count = 0;

        Ivar *ivars = class_copyIvarList([PYPeople class], &count);

        

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

            // 取出i位置对应的成员变量

            Ivar ivar = ivars[i];

            

            // 查看成员变量

            const char *name = ivar_getName(ivar);

            

            // 归档

            NSString *key = [NSString stringWithUTF8String:name];

            id value = [decoder decodeObjectForKey:key];

            

            // 设置到成员变量身上

            [self setValue:value forKey:key];

        }

        

        free(ivars);

    }

    

    return self;

}

@end

 

runtime机制首先要了解下面几个问题 1相关的头文件和函数 1> 头文件

  • <objc/runtime.h>

  • <objc/message.h> 利用头文件,我们可以查看到runtime中的各个方法!

2> 相关应用

  • NSCoding(归档和解档, 利用runtime遍历模型对象的所有属性)
  • 字典 --> 模型 (利用runtime遍历模型对象的所有属性, 根据属性名从字典中取出对应的值, 设置到模型的属性上)
  • KVO(利用runtime动态产生一个类)
  • 用于封装框架(想怎么改就怎么改) 这就是我们runtime机制的只要运用方向

3> 相关函数

  • objc_msgSend : 给对象发送消息
  • class_copyMethodList : 遍历某个类所有的方法
  • class_copyIvarList : 遍历某个类所有的成员变量
  • class_..... 这是我们学习runtime必须知道的函数!

4.必备常识 1> Ivar : 成员变量 2> Method : 成员方法 从上面例子中我们看到我们定义的成员变量,如果要是动态创建方法,可以使用Method,

转载于:https://www.cnblogs.com/qinxiaoguang/p/5600980.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值