美文网首页
保存自定义对象数组、字典到文件

保存自定义对象数组、字典到文件

作者: 不舍 | 来源:发表于2016-03-22 16:32 被阅读165次

在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];
}

相关文章

  • 保存自定义对象数组、字典到文件

    在ios中,要保存普通的数组到文件可以直接调用-wirteToFile:atomically:方法写入,并且可以通...

  • 文件操作

    NSUserDefault:保存少量的数据(几张的图片,字符串,小量的数组 字典 某个对象) 文件:(图片、视频)...

  • Note 24 ScrollView,观察者,两种文件管理结合

    JSONFile 将对象属性保存到字典里 然后将字典JSON化 用NSData的writeTo 方法保存到文件中 ...

  • iOS归档看这篇就够了

    归档的作用 之前将数据存储到本地,只能是字符串、数组、字典、NSNuber、BOOL等容器类对象,不能将自定义对象...

  • iOS中plist文件

    plist文件 plist文件储存本地数据的一种方式 json实例对象,字典或者数组 跟目录 写入数据到plist...

  • IOS应用开发,plist方式保存数据以及Preferences

    plist方式保存数据plist可以保存的类型为数组与字典.在介绍plist文件保存之前,先介绍几个方法。 注意事...

  • 归档 存储数据

    归档一般都是保存自定义对象的时候,使用归档.因为plist文件不能够保存自定义对象. 如果一个字段当中保存有自定义...

  • 归档 存储数据

    归档一般都是保存自定义对象的时候,使用归档.因为plist文件不能够保存自定义对象.如果一个字段当中保存有自定义对...

  • iOS开发之--一种自定义对象快速保存方法

    此方法基本思路是:保存对象前利用反射机制获得该对象的每个属性,再转化为字典,最后将字典写入文件。 读取对象时先将文...

  • IOS plist 文件写入与读取

    数组写入plist文件(文件储存到cache路径下) 字典写入plist文件 将字典数组写入plist文件

网友评论

      本文标题:保存自定义对象数组、字典到文件

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