首页 > 代码库 > 利用归档保存数组数据
利用归档保存数组数据
1首先创建一个模型类,一定要遵守NSCoding协意。
@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测试归档
@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
利用归档保存数组数据
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。