IOS --使用NSCoding归档和反归档


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

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

@interface Student : NSObject <NSCoding>
  • 1

然后再.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"]; }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
/** * 从文件中解析对象时会调用 * 在这个方法中说清楚哪些属性需要存储 */ - (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; }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

控制器中得读写方法。

- (IBAction)save { // 1.新的模型对象 Student *stu = [[Student alloc] init]; stu.no = @"42343254"; stu.age = 20; stu.height = 1.55; // 2.归档模型对象 // 2.1.获得Documents的全路径 NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; // 2.2.获得文件的全路径 NSString *path = [doc stringByAppendingPathComponent:@"stu.data"]; // 2.3.将对象归档 [NSKeyedArchiver archiveRootObject:stu toFile:path]; }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

反归档(读取)

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM