码迷,mamicode.com
首页 > 其他好文 > 详细

反射实现NSCodingProtocol 帮助类

时间:2014-08-30 20:20:41      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   使用   io   for   文件   div   log   

// .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 帮助类

标签:style   blog   color   使用   io   for   文件   div   log   

原文地址:http://www.cnblogs.com/1oo1/p/3946756.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!