反射实现NSCodingProtocol 帮助类

// .h文件
#import
<Foundation/Foundation.h> @interface NSCodingProtocolHelper : NSObject +(void)encodeWithCoder:(NSCoder *)aCoder andObj:(id)obj; +(id)initWithCoder:(NSCoder *)aDecoder andObj:(id)obj; @end

 

// .m文件
#import "NSCodingProtocolHelper.h" #import <objc/runtime.h> //反射需要用到的头文件 @implementation NSCodingProtocolHelper +(void)encodeWithCoder:(NSCoder *)aCoder andObj:(id)obj { unsigned int outCount; objc_property_t *properties = class_copyPropertyList([obj class], &outCount); for (int i = 0; i < outCount; i++) { objc_property_t *thisProperty = properties + i; NSString *propertyName = [NSString stringWithUTF8String:property_getName(*thisProperty)]; [aCoder encodeObject:[obj valueForKey:propertyName] forKey:propertyName]; } } +(id)initWithCoder:(NSCoder *)aDecoder andObj:(id)obj { unsigned int outCount; objc_property_t *properties = class_copyPropertyList([obj class], &outCount); for (int i = 0; i < outCount; i++) { objc_property_t *thisProperty = properties + i; NSString *propertyName = [NSString stringWithUTF8String:property_getName(*thisProperty)]; [obj setValue:[aDecoder decodeObjectForKey:propertyName] forKey:propertyName]; } return obj; } @end

使用方法:

在要实现NSCodingProtocle的类中重写 initWithCoder: 和encodeWithCoder: 方法,

例如:

-(void) encodeWithCoder:(NSCoder *)aCoder
{
    [NSCodingProtocolHelper encodeWithCoder:aCoder andObj:self];
    
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
    return [NSCodingProtocolHelper initWithCoder:aDecoder andObj:selfl];
}

 

property_getAttributes 方法可以获得属性,

[NSString stringWithUTF8String:property_getAttributes(*property)]得到类似 

Ti,N,V_uid

或者 

T@"NSString",C,N,V_name

这样的字符串,通过截取第二个字符可以判断属性的类型,@代表对象。

  

转载于:https://www.cnblogs.com/1oo1/p/3946756.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值