首页 > 代码库 > 反射实现NSCodingProtocol 帮助类
反射实现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];}
反射实现NSCodingProtocol 帮助类
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。