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);
}