美文网首页
使用YYModel的归档

使用YYModel的归档

作者: ChangeWorld | 来源:发表于2016-07-19 13:59 被阅读1753次

    归档这种存储方式,比较轻量和高效的. 之前不怎么使用,现在用起来了,几个笔记也好! 以下是随手写的一个示例Demo ,依赖于YYModel ,自己不想用第三方库,那就要一个个的写编码解码,或者使用runtime键值映射稍微简单点儿,我这里不重复造轮子了.

    #import <Foundation/Foundation.h>
    #import "YYModel.h"
    
    @interface Person : NSObject<NSCoding, NSCopying>
    
    @property (nonatomic,copy) NSString *name;
    
    @property (nonatomic,copy) NSString *age;
    
    @end
    
    
    
    #import "Person.h"
    
    @implementation Person
    
    //重写以下几个方法 
    - (void)encodeWithCoder:(NSCoder*)aCoder {
        [self yy_modelEncodeWithCoder:aCoder];
    }
    
    - (id)initWithCoder:(NSCoder*)aDecoder
    {
        self = [super init];
        return [self yy_modelInitWithCoder:aDecoder];
    }
    
    - (id)copyWithZone:(NSZone*)zone {
        return [self yy_modelCopy];
    }
    
    - (NSUInteger)hash {
        return [self yy_modelHash];
    }
    
    - (BOOL)isEqual:(id)object {
        return [self yy_modelIsEqual:object];
    }
    
    @end
    
    
    #import <UIKit/UIKit.h>
    
    @interface ViewController : UIViewController
    
    
    @end
    
    
    
    #import "ViewController.h"
    #import "Person.h"
    
    #define KDocumentPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) lastObject]
    
    #define kPersonInfoPath [KDocumentPath stringByAppendingPathComponent:@"personInfo.archiver"]
    
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
    //先存档  然后屏蔽这段代码  看看是否归档到了本地
    //    NSMutableArray *dataArray =[NSMutableArray array];
    //
    //    for (NSInteger i = 10; i < 20 ; i++) {
    //        Person * p =[Person new];
    //        p.name = [NSString stringWithFormat:@"name==-%ld",i];
    //        p.age = [NSString stringWithFormat:@"+++%ld岁",i];
    //        [dataArray addObject:p];
    //    }
    //
    //    BOOL ret =  [NSKeyedArchiver archiveRootObject:dataArray toFile:kPersonInfoPath];
    //
    //    if (ret) {
    //        NSLog(@"归档成功");
    //    }else{
    //        NSLog(@"归档失败");
    //    }
    
        NSArray *arr =[NSKeyedUnarchiver unarchiveObjectWithFile:kPersonInfoPath];
        for (Person *p in arr) {
            NSLog(@"名字%@,年龄%@", p.name,p.age);
        }
    
    }
    
    @end
    

    相关文章

      网友评论

          本文标题:使用YYModel的归档

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