zoukankan      html  css  js  c++  java
  • 反射实现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

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

      

  • 相关阅读:
    广度优先搜索-八数码问题
    广度优先搜索-鸣人和佐助
    广度优先搜索-迷宫问题
    广度优先搜索-抓住那头牛
    Unity面试题汇总(第一部分)
    独立项目-Socket通讯 应用/客户端和服务器的简单通讯-04
    独立项目-Socket通讯 服务器端代码-04
    独立项目-Socket通讯 客户端代码-03
    独立项目-Socket通讯 发送数据包和接收数据包过程图-02
    独立项目-Socket通讯 服务器端架构图-01
  • 原文地址:https://www.cnblogs.com/1oo1/p/3946756.html
Copyright © 2011-2022 走看看