使用runtime归档模型对象

在开发中经常需要对一些对象进行保存,当然这是一些很轻量级的,我们首先会想到使用NSUserDefaults进行保存,但是NSUserDefaults所能直接保存的对象类型也是有限的,比如NSArray,NSData,NSDictionary,NSNumber,NSString,对于我们自己建立的模型对象,NSUserDefaults直接保存的话,就有点力不从心了,这时,我们往往要对模型对象进行归档,归档虽说实现简单,但是,试想一些,如果你的模型成员比较多,手动实现很费时间,可以新建一个NSObject的分类,使用runtime遍历属性实现归档

. h 文件
//
//  DVVCoding.h
//  DVVCoding <https://github.com/devdawei/DVVCoding.git>
//
//  Created by 大威 on 2016/11/21.
//  Copyright © 2016年 devdawei. All rights reserved.
//

#import <Foundation/Foundation.h>

@protocol DVVCodingDelegate <NSObject>

@optional

/**
 如果有不想缓存的属性,通过此代理方法返回就可以了
 */
+ (NSArray *)dvv_codingIgnoreProperties;

@end

@interface NSObject (DVVCoding)

/**
 *  解码(从文件解析对象)
 */
- (void)dvv_decode:(NSCoder *)decoder;
/**
 *  编码(将对象写入文件)
 */
- (void)dvv_encode:(NSCoder *)encoder;


/**
 *  属性归档的实现
 */
#define DVVCodingImplementation \
- (instancetype)initWithCoder:(NSCoder *)aDecoder \
{ \
self = [super init]; \
if (self) { \
[self dvv_decode:aDecoder]; \
} \
return self; \
} \
\
- (void)encodeWithCoder:(NSCoder *)coder \
{ \
[self dvv_encode:coder]; \
}

@end
. m 文件
//
//  DVVCoding.m
//  DVVCoding <https://github.com/devdawei/DVVCoding.git>
//
//  Created by 大威 on 2016/11/21.
//  Copyright © 2016年 devdawei. All rights reserved.
//

#import "DVVCoding.h"
#import <objc/runtime.h>

typedef NS_ENUM(NSUInteger, DVVCodingType)
{
    DVVCodingTypeEncode,
    DVVCodingTypeDecode,
};

@implementation NSObject (DVVCoding)


- (void)dvv_encode:(NSCoder *)encoder
{
    [self dvv_codingFor:encoder type:DVVCodingTypeEncode];
}

- (void)dvv_decode:(NSCoder *)decoder
{
    [self dvv_codingFor:decoder type:DVVCodingTypeDecode];
}

- (void)dvv_codingFor:(NSCoder *)coder type:(DVVCodingType)type
{
    NSArray *ignoreProperties = nil;
    if ([[self class] respondsToSelector:@selector(dvv_codingIgnoreProperties)])
    {
        ignoreProperties = (NSArray *)[[self class] performSelector:@selector(dvv_codingIgnoreProperties)];
    }
    
    if (!ignoreProperties) ignoreProperties = [NSArray array];
    // 添加默认忽略的属性
    NSMutableArray *defaultIgnoreProperties = [NSMutableArray arrayWithObjects:@"hash", @"superclass", @"description", @"debugDescription", nil];
    ignoreProperties = [defaultIgnoreProperties arrayByAddingObjectsFromArray:ignoreProperties];
    
    unsigned int count;
    // 获取属性列表
    objc_property_t *properties = class_copyPropertyList(self.class, &count);
    
    for (unsigned int i = 0; i < count; i++)
    {
        // 获取一个属性
        objc_property_t property = properties[i];
        // 获取一个属性名
        const char *name = property_getName(property);
        NSString *propertyName = [NSString stringWithUTF8String:name];
        
        // 过滤属性
        if (ignoreProperties)
        {
            BOOL flage = NO;
            for (NSString *ignorePropertyName in ignoreProperties)
            {
                if ([propertyName isEqualToString:ignorePropertyName])
                {
                    flage = YES;
                    break;
                }
            }
            if (flage)
            {
                continue;
            }
        }
        
        // 用来存储一个属性值
        NSString *propertyValue = nil;
        
        // 编码
        if (DVVCodingTypeEncode == type)
        {
            propertyValue = [self valueForKey:propertyName];
            if(propertyValue) [coder encodeObject:propertyValue forKey:propertyName];
        }
        // 解码
        else if (DVVCodingTypeDecode == type)
        {
            propertyValue = [coder decodeObjectForKey:propertyName];
            if(propertyValue) [self setValue:propertyValue forKey:propertyName];
        }
    }
    // 释放
    free(properties);
}

@end
直接在模型对象的implementation里调用宏
#import "MMRDMUserInfo.h"

@implementation MMRDMUserInfo

// 调用这句宏定义,即可实现对象归档,不用自己再对每一个属性写繁琐的编码和解码
DVVCodingImplementation

/**
 如果有不想缓存的属性,通过此代理方法返回

 @return 忽略列表
 */
+ (NSArray *)dvv_codingIgnoreProperties
{
    return @[ @"property_1", @"property_2" ];
}

@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,219评论 30 472
  • 前言: 在程序开发中,数据层永远是程序的核心结构之一。对这些数据的加工处理是代码中能体现技术水平的一大模块,比如数...
    麦穗0615阅读 1,477评论 3 22
  • 转载自:http://www.mamicode.com/info-detail-957988.html 1、iOS...
    哆啦_阅读 2,337评论 0 2
  • iOS 開発の結構 画面 UI UIWebview [[UIApplication sharedApplicati...
    RencaiXiong阅读 606评论 0 0
  • Maybe,I am sensitive. 我对光线有一种近乎偏执的“挑剔”。每天睡觉前,我总会让舍友把台灯调暗一...
    看云的LJH阅读 670评论 1 4