iOS开发??保存自定义对象数组、字典到文件

本文介绍如何在iOS中保存包含自定义对象的数组至文件并读取。首先需使自定义对象符合NSCoding协议,然后利用NSKeyedArchiver和NSKeyedUnarchiver进行归档与解档。

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

iOS开发??保存自定义对象数组、字典到文件

2014-11-25 22:26

在ios中,要保存普通的数组到文件可以直接调用-wirteToFile:atomically:方法写入,并且可以通过NSArray的方法-initWithContentOfFile:来读文件初始化数组。然而,当要保存的数组中存储的数据对象是自定义对象时,就得通过对象归档的方法来实现了,具体来说


一、自定义对象实现归档协议,并实现方法- (id)initWithCoder:和方法- (void)encodeWithCoder:

@interface CourseModel : CYZBaseModel <NSCoding>


- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self) {
        self.courseName = [aDecoder decodeObjectForKey:@"courseName"];
        self.courseTeacher = [aDecoder decodeObjectForKey:@"courseTeacher"];
        self.courseTime = [aDecoder decodeObjectForKey:@"courseTime"];
        self.courseLocation = [aDecoder decodeObjectForKey:@"courseLocation"];
        self.shouldUseTip = [aDecoder decodeBoolForKey:@"shouldUseTip"];
        self.row = [aDecoder decodeIntegerForKey:@"row"];
        self.section = [aDecoder decodeIntegerForKey:@"section"];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.courseName forKey:@"courseName"];
    [aCoder encodeObject:self.courseTeacher forKey:@"courseTeacher"];
    [aCoder encodeObject:self.courseTime forKey:@"courseTime"];
    [aCoder encodeObject:self.courseLocation forKey:@"courseLocation"];
    [aCoder encodeBool:self.shouldUseTip forKey:@"shouldUseTip"];
    [aCoder encodeInteger:self.row forKey:@"row"];
    [aCoder encodeInteger:self.section forKey:@"section"];
}


二、获得保存文件的路径

- (NSString *)filePath
{
    return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"course.plist"];
}




三、调用NSKeyedArchived类的类方法:- (void)archiveRootObject:toFile:写入文件 

    NSString *path = [self filePath];
    [NSKeyedArchiver archiveRootObject:self.allCourses toFile:path];



四、调用NSKeyedUnarchiver类的类方法:- (id)unarchiveObjectWithFile:读文件

    NSString *path = [self filePath];
    self.allCourses = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    if (self.allCourses == nil) {
        self.allCourses = [NSMutableArray array];
    }


转载于:https://my.oschina.net/u/2329800/blog/625115

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值