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

通过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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容