iOS 用本地文件保存自定义模型

这篇博客探讨了在iOS应用中如何使用本地文件来保存自定义模型数据。通过遵循<NSCopying>协议,开发者可以实现将自定义模型归档到本地文件,以便后续读取和使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


iOS中,保存数据有四种方法,归档、文件、NSUserDefaults和sqlite数据库。每一种方式都有其特定的类型,在上一篇文章中介绍了用NSUserDefaults保存自定义模型的数据,这一篇来介绍一下用本地文件保存自定义模型的数据。


在自定义模型中,要遵守<NSCopying>协议

点h

#import <Foundation/Foundation.h>

@interface ChatLogModel : NSObject<NSCopying>

@property(nonatomic,copy)NSString *name;
@property(nonatomic,assign)BOOL isVideo;
@property(nonatomic,strong)NSString *date;

@end

点m

#import "ChatLogModel.h"

#define NAME @"name"
#define ISVIDEO @"isVideo"
#define DATE @"date"

@implementation ChatLogModel

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

    [aCoder encodeObject:self.name forKey:NAME];
    [aCoder encodeBool:self.isVideo forKey:ISVIDEO];
    [aCoder encodeObject:self.date forKey:DATE];
}
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init]) {
        self.name = [aDecoder decodeObjectForKey:NAME];
        self.isVideo = [aDecoder decodeBoolForKey:ISVIDEO];
        self.date = [aDecoder decodeObjectForKey:DATE];
        
    }
    
    return self;
}

@end


在使用的时候

-(void)storeChatLogWithFile
{
//    获取路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"chatlog.plist"];
    NSFileManager *fileM = [NSFileManager defaultManager];
//    判断文件是否存在,不存在则直接创建,存在则直接取出文件中的内容
    if (![fileM fileExistsAtPath:filePath]) {
        [fileM createFileAtPath:filePath contents:nil attributes:nil];
    }
    NSMutableArray *chatLogArray = [NSMutableArray arrayWithContentsOfFile:filePath];
    if ((chatLogArray.count == 0)) {
        chatLogArray = [NSMutableArray arrayWithCapacity:1];
    }
    
//    要保存的自定义模型
    ChatLogModel *chatmodel = [[ChatLogModel alloc] init];
    chatmodel.name = @"张三";
    chatmodel.isVideo = YES;
//    获取当前时间
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM-dd hh:mm:ss"];
    NSString *dateString = [formatter stringFromDate:currentDate];
    chatmodel.date = dateString;
 
    [chatLogArray addObject:chatmodel];

/*
    这是正常的保存和取出数组内容到文件
    存
    [chatLogArray writeToFile:filePath atomically:YES];
    取
    NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:filePath];
*/
 
    
//    注意 数组中保存的是自定义模型,要想把数组保存在文件中,应该用下面的方法
//    存
    [NSKeyedArchiver archiveRootObject:chatLogArray toFile:filePath];
//    取
    NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    NSLog(@"array:%@",array);

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值