美文网首页
iOS:序列化与反序列化

iOS:序列化与反序列化

作者: 狠狠狠_6022 | 来源:发表于2017-05-18 16:41 被阅读0次

    一般情况把一个模型存在本地,一般情况使用序列化与反序列化的基本代码去实现比较麻烦,使用runtime(so easy),具体代码实现如下

    1.创建一个student类 .h文件

    @interface Student : NSObject

    @property (nonatomic, copy) NSString *name;

    @property (nonatomic, copy) NSString *age;

    2.student.m 主要实现方法

    #import "Student.h"

    #import <objc/runtime.h>

    @implementation Student

    //对象编码和解码

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

    unsigned int count = 0;

    //获得指向该类所有属性的指针

    objc_property_t *propert = class_copyPropertyList([Student class], &count);

    for (int i = 0 ; i < count; i++) {

    //根据objc_property_t获得其属性的名称--->C语言的字符串

    objc_property_t pro = propert[i];

    const char *name = property_getName(pro);

    NSString  *key = [NSString stringWithUTF8String:name];

    //编码每个属性,利用KVC取出每个属性对应的数值

    [aCoder encodeObject:[self valueForKey:key] forKey:key];

    NSString *vc = [self valueForKey:key];

    NSLog(@"123=======%@",vc);

    }

    }

    -(instancetype)initWithCoder:(NSCoder *)aDecoder{

    if (self = [super init]) {

    unsigned int count = 0;

    objc_property_t *property = class_copyPropertyList([Student class], &count);

    for (int i = 0; i < count; i++) {

    objc_property_t proc = property[i];

    const char *name =  property_getName(proc);

    NSString *key = [NSString stringWithUTF8String:name];

    NSString *vc = [self valueForKey:key];

    vc = [aDecoder decodeObjectForKey:key];

    }

    }

    return self;

    }

    @end

    3.ViewController的具体实现方法

    存模型的方法

    Student *student = [Student new];

    student.name = @"测试";

    student.age = @"20";

    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:student];

    [[NSUserDefaults standardUserDefaults]setObject:data forKey:@"student"];

    [[NSUserDefaults standardUserDefaults]synchronize];

    取模型的方法

    NSData *data = [[NSUserDefaults standardUserDefaults]objectForKey:@"student"];

    Student *student = [NSKeyedUnarchiver unarchiveObjectWithData:data];

    相关文章

      网友评论

          本文标题:iOS:序列化与反序列化

          本文链接:https://www.haomeiwen.com/subject/evrhxxtx.html