runtime使用 自定义数据类型的编码解码

2018-11-03  本文已影响0人  回传妙手

通过runtime 遍历自定义model的所有属性实现归档解档操作。

要实现我们自定义的model能够自动解档归档,要遵守NSCoding协议

#import <Foundation/Foundation.h>

@interface siteModel : NSObject<NSCoding>

@property (nonatomic,copy) NSString *siteName;

@property (nonatomic, copy) NSString *siteId;

@end

.m中实现两个协议方法

//归档,将model数据存储本地

- (void)encodeWithCoder:(NSCoder *)aCoder;

//解档,从本地数据中生成model

- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder;

.m方法实现

#import "siteModel.h"

#import <objc/runtime.h>

@implementation siteModel

{

    NSString *subSiteName;

}

- (instancetype)initWithCoder:(NSCoder *)aDecoder

{

    if ([super init])

    {

        unsigned int ivar_count;

        Ivar *ivars = class_copyIvarList([self class], &ivar_count);

        for (int i = 0; i< ivar_count; i++)

        {

            Ivar ivar = ivars[i];

            NSString *ivarName = [NSString stringWithUTF8String:ivar_getName(ivar)];

            [self setValue:[aDecoder decodeObjectForKey:ivarName] forKey:ivarName];

        }

    }

    return self;

}

- (void)encodeWithCoder:(NSCoder *)aCoder

{

    unsigned int ivar_count;

    Ivar *ivars = class_copyIvarList([self class], &ivar_count);

    for (int i = 0; i< ivar_count; i++)

    {

        Ivar ivar = ivars[i];

        NSString *ivarName = [NSString stringWithUTF8String:ivar_getName(ivar)];

        [aCoderencodeObject:[self valueForKey:ivarName] forKey:ivarName];

    }

}

@end

在controller中使用

//归档

siteModel *fatherSite = [[siteModel alloc]init];

    fatherSite.siteName = @"北京";

    fatherSite.siteId = @"12300";

    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) firstObject];

    NSString *filePath = [documentPath stringByAppendingString:@"modelFile"];

    [NSKeyedArchiver archiveRootObject:fatherSite toFile:filePath];

//解档

    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) firstObject];

    NSString *filePath = [documentPath stringByAppendingString:@"modelFile"];

    siteModel *localSite = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

    NSLog(@"siteName:%@ siteId:%@",localSite.siteName,localSite.siteId);

 siteName:北京 siteId:12300

上一篇下一篇

猜你喜欢

热点阅读