您好,欢迎来到伴沃教育。
搜索
您的当前位置:首页归档-把自定义的对象存放在文件中

归档-把自定义的对象存放在文件中

来源:伴沃教育
#import <Foundation/Foundation.h>

// 如果想将一个自定义对象保存到文件中必须实现NSCoding协议
@interface UserModel : NSObject<NSCoding>

///用户ID
@property (nonatomic , assign) NSInteger identifie;

///姓名
@property (nonatomic , copy) NSString * name;

///性别
@property (nonatomic , copy) NSString * sex;

///年龄
@property (nonatomic , assign) NSInteger age;

///手机
@property (nonatomic , copy) NSString * mobile;

///头像ID
@property (nonatomic , assign) NSInteger  image_id;

///头像路径
@property (nonatomic , copy) NSString * image_path;

@end
#import "UserModel.h"

@implementation UserModel

// 当将一个自定义对象保存到文件的时候就会调用该方法
// 在该方法中说明如何存储自定义对象的属性
// 也就说在该方法中说清楚存储自定义对象的哪些属性
-(void)encodeWithCoder:(NSCoder *)aCoder
{
    NSLog(@"调用了encodeWithCoder:方法");
    [aCoder encodeInteger:self.identifie forKey:@"identifie"];
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeInteger:self.age forKey:@"age"];
    [aCoder encodeObject:self.sex forKey:@"sex"];
    [aCoder encodeObject:self.mobile forKey:@"mobile"];
    [aCoder encodeInteger:self.image_id forKey:@"image_id"];
    [aCoder encodeObject:self.image_path forKey:@"image_path"];

}

// 当从文件中读取一个对象的时候就会调用该方法
// 在该方法中说明如何读取保存在文件中的对象
// 也就是说在该方法中说清楚怎么读取文件中的对象
-(id)initWithCoder:(NSCoder *)aDecoder
{
    NSLog(@"调用了initWithCoder:方法");
    //注意:在构造方法中需要先初始化父类的方法
    if (self=[super init]) {
        self.identifie=[aDecoder decodeIntegerForKey:@"identifie"];
        self.name=[aDecoder decodeObjectForKey:@"name"];
        self.age=[aDecoder decodeIntegerForKey:@"age"];
        self.sex=[aDecoder decodeObjectForKey:@"sex"];
        self.mobile=[aDecoder decodeObjectForKey:@"mobile"];
        self.image_id=[aDecoder decodeIntegerForKey:@"image_id"];
        self.image_path=[aDecoder decodeObjectForKey:@"image_path"];
     }
    return self;
}

@end

VC

- (IBAction)add:(UIButton *)sender {
    UserModel * model = [[UserModel alloc]init];
    model.identifie   = 1111;
    model.name        = @"刘哥哥";
    model.sex         = @"男";
    model.age         = 23;
    model.mobile      = @"13612345678";
    model.image_id    = 123;
    model.image_path  = 
    
    NSString * path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject]stringByAppendingPathComponent:@"user.text"];
     NSLog(@"%@",path);
     //将自定义的对象保存到文件中
     [NSKeyedArchiver archiveRootObject:model toFile:path];
}

- (IBAction)search:(UIButton *)sender {
    NSString * path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject]stringByAppendingPathComponent:@"user.text"];
    NSLog(@"path=%@",path);
     //2.从文件中读取对象
    UserModel * model =[NSKeyedUnarchiver unarchiveObjectWithFile:path];
    NSLog(@"%@",model.name);
}

Copyright © 2019- bangwoyixia.com 版权所有 湘ICP备2023022004号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务