一般通过NSKeyedArchiver来存储一般的对象:
重点在encode和decode
- - (IBAction)save:(id)sender {
- MrPerson *person = [[MrPerson alloc]init];
- person.name = @"Ranran";
- person.age = 16;
- person.height = 1.62;
- [NSKeyedArchiver archiveRootObject:person toFile:@"/Users/misaka/Desktop/0410/p.Data"];
- }
读取数据:
- - (IBAction)read:(id)sender {
- MrPerson *person = [NSKeyedUnarchiver unarchiveObjectWithFile:@"/Users/misaka/Desktop/0410/p.Data"];
- NSLog(@"%@---%ld-----%f",person.name,(long)person.age,person.height);
- }
Person类头文件中的设置:
- #import <Foundation/Foundation.h>
- @interface MrPerson : NSObject<NSCoding>
- @property (nonatomic,copy) NSString* name;
- @property (nonatomic,assign) NSInteger age;
- @property (nonatomic,assign) double height;
- @end
Person类实现文件中的设置:
- #import "MrPerson.h"
- @implementation MrPerson
- - (void)encodeWithCoder:(NSCoder *)aCoder
- {
- [aCoder encodeObject:self.name forKey:@"name"];
- [aCoder encodeInteger:self.age forKey:@"age"];
- [aCoder encodeDouble:self.height forKey:@"height"];
- }
- - (id)initWithCoder:(NSCoder *)aDecoder
- {
- if (self = [super init]) {
- self.name = [aDecoder decodeObjectForKey:@"name"];
- self.age = [aDecoder decodeIntegerForKey:@"age"];
- self.height = [aDecoder decodeDoubleForKey:@"height"];
- }
- return self;
- }
- @end