存储】使用NSCoding归档和反归档

iOS开发中要想存储对象可以使用NSCoding,要想存储的对象必须实验NSCoding协议

比如我们要存储一个Student对象,那么Student类必须遵循NSCoding协议,然后实现NSCoding中得两个方法。

@interface Student : NSObject <NSCoding>

然后再.m文件中实现encodeWithCoder:(存)和initWithCoder:(读)方法,这样就告诉了程序这个对象应该怎么存,要存那些属性,,以及需要怎么读!

/** * 将某个对象写入文件时会调用 * 在这个方法中说清楚哪些属性需要存储 */- (void)encodeWithCoder:(NSCoder *)encoder{[encoder encodeObject:self.no forKey:@”no”];[encoder encodeInt:self.age forKey:@”age”];[encoder encodeDouble:self.height forKey:@”height”];}/** * 从文件中解析对象时会调用 * 在这个方法中说清楚哪些属性需要存储 */- (id)initWithCoder:(NSCoder *)decoder{if (self = [super init]) {// 读取文件的内容self.no = [decoder decodeObjectForKey:@”no”];self.age = [decoder decodeIntForKey:@”age”];self.height = [decoder decodeDoubleForKey:@”height”];}return self;}

控制器中得读写方法。

– (IBAction)save {// 1.新的模型对象Student *stu = [[Student alloc] init];stu.no = @”42343254″;stu.age = 20;stu.height = 1.55;*doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];// 2.2.获得文件的全路径NSString *path = [doc stringByAppendingPathComponent:@”stu.data”];// 2.3.将对象归档[NSKeyedArchiver archiveRootObject:stu toFile:path];}

反归档(读取)

– (IBAction)read {// 1.获得Documents的全路径NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];// 2.获得文件的全路径NSString *path = [doc stringByAppendingPathComponent:@”stu.data”];// 3.从文件中读取MJStudent对象Student *stu = [NSKeyedUnarchiver unarchiveObjectWithFile:path];}

只有经历过地狱般的折磨,才有征服天堂的力量。

存储】使用NSCoding归档和反归档

相关文章:

你感兴趣的文章:

标签云: