1. First, create a model class and follow the nscoding agreement.
@interface Contact : NSObject <NSCoding>@property (nonatomic, copy) NSString *name;@property (nonatomic, copy) NSString *phone;@endimplementation Contact- (void)encodeWithCoder:(NSCoder *)encoder{ [encoder encodeObject:self.name forKey:@"name"];//读取时属性对应的Key [encoder encodeObject:self.phone forKey:@"phone"];}- (id)initWithCoder:(NSCoder *)decoder{ if (self = [super init]) { self.name = [decoder decodeObjectForKey:@"name"]; //归档时属性对应的Key self.phone = [decoder decodeObjectForKey:@"phone"]; } return self;}@end
2. Test Archiving
@interface ContactsTest : UITableViewController@property (nonatomic, strong) NSMutableArray *array@end@implementation MJContactsViewController-(void)writ{ //创建归档文件路径。“contacts.data”可以随便写 NSString *path=[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"contacts.data"] // 归档数组 [NSKeyedArchiver archiveRootObject:self. array toFile: path]; }-(void)read{ NSString *path=[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"contacts.data"] self.array = [NSKeyedUnarchiver unarchiveObjectWithFile:path]; }@end
Use archive to save array data