美文网首页
iOS 使用RGArchiver存储OC对象

iOS 使用RGArchiver存储OC对象

作者: _RG | 来源:发表于2020-04-08 17:01 被阅读0次

    iOS自定义对象存储,必须继承NSCoding协议,实现对应的- (void)encodeWithCoder:(NSCoder *)coder;- (nullable instancetype)initWithCoder:(NSCoder *)coder; 方法

    RGArchiver采用runtime运行时特性,自动给对象添加encodeWithCoder,initWithCoder方法,在对应的方法中获取对象所有成员变量,进行持久化存储

    github地址

    使用 pod 'RGArchiver'下载框架即可直接使用,如果pod失败,需要先执行pod repo update更新本地pod库

    示例

    #import <Foundation/Foundation.h>
    
    
    @interface User : NSObject
    
    @property(nonatomic,assign) NSInteger age;
    
    @property(nonatomic,copy) NSString *name;
    
    @property(nonatomic,copy) NSString *address;
    
    @end
    
    
    @implementation User
    
    @end
    
    
    
    - (IBAction)archiverUser:(id)sender {
        
        User *user = [User new];
        user.name = @"小明";
        user.age = 17;
        [RGArchiver archiverObject:user toFile:[self userPath]];
    
    }
    
    - (IBAction)unarchiverUser:(id)sender {
        
        User *user = [RGArchiver unArchiverObjectOfObjectClass:[User class] fromFile:[self userPath]];
        NSLog(@"age = %ld,name = %@",user.age,user.name);
        
    }
    - (NSString *)userPath {
        
        NSString *path  = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"user.plist"];
        NSLog(@"userPath = %@",path);
        return path;
    }
    

    User中类并没有实现NSCoding协议,即可实现User对象的存储

    相关文章

      网友评论

          本文标题:iOS 使用RGArchiver存储OC对象

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