iOS 数据的归档(NSKeyedArchiver )与数据的解档(NSKeyedUnarchiver) 加密 提高安全性

 1 #import <UIKit/UIKit.h>
 2 
 3 @interface ViewController : UIViewController
 4 /**
 5  *  创建归档与解档的按钮
 6  */
 7 @property(strong,nonatomic) UIButton *btnAchiver;
 8 @property(strong,nonatomic) UIButton *btnUnAchiver;
 9 
10 
11 #import "ViewController.h"
12 //宏定义 根目录
13 #define PATH [NSHomeDirectory() stringByAppendingPathComponent:@"test.add"]
14 @interface ViewController ()
15 
16 @end
17 
18 @implementation ViewController
19 
20 - (void)viewDidLoad
21 {
22     [super viewDidLoad];
23     NSLog(@"%@",PATH);
24     //创建归档的按钮
25     self.btnAchiver=[[UIButton alloc] initWithFrame:CGRectMake(100, 100, 200, 50)];
26     //为按钮添加背景色
27     self.btnAchiver.backgroundColor=[UIColor redColor];
28     //为按钮添加标题
29     [self.btnAchiver setTitle:@"数据归档" forState:UIControlStateNormal];
30     //按钮触发事件
31     [self.btnAchiver addTarget:self action:@selector(DataArchiver) forControlEvents:UIControlEventTouchUpInside];
32     //将按钮添加到父视图上
33     [self.view addSubview:self.btnAchiver];
34     
35     //创建解档的按钮
36     self.btnUnAchiver=[[UIButton alloc] initWithFrame:CGRectMake(100, 200, 200, 50)];
37     //为按钮添加背景色
38     self.btnUnAchiver.backgroundColor=[UIColor redColor];
39     //为按钮添加标题
40     [self.btnUnAchiver setTitle:@"数据解档" forState:UIControlStateNormal];
41     //按钮触发事件
42     [self.btnUnAchiver addTarget:self action:@selector(DataUnArchiver) forControlEvents:UIControlEventTouchUpInside];
43     //将按钮添加到父视图上
44     [self.view addSubview:self.btnUnAchiver];
45 
46 }
47 //事件 归档
48 -(void)DataArchiver
49 {
50     //创建归档的集合
51     NSArray *arr=@[@"yj",@"lm",@"tt"];
52     //创建归档的字符串
53     NSString *str=@"guiyangxueyuan";
54     //集合和字符串是要归档
55     BOOL bol=YES;
56     //初始化可变数据
57     NSMutableData *data=[NSMutableData data];
58     //初始化归档
59    NSKeyedArchiver *Archiver= [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
60     //把集合归档
61     [Archiver encodeObject:arr forKey:@"arr"];
62     //把字符串归档
63     [Archiver encodeObject:str forKey:@"str"];
64     //是要归档
65     [Archiver encodeBool:bol forKey:@"bol"];
66     //完成归档
67     [Archiver finishEncoding];
68     //把数据归档到PATH目录
69     BOOL bol2= [data writeToFile:PATH atomically:YES];
70     NSLog(@"%d",bol2);
71     
72 }
73 //事件 解档
74 -(void)DataUnArchiver
75 {
76     //把解档数据存在PATH目录下
77     NSData *data=[NSData dataWithContentsOfFile:PATH];
78     //把解档的放在数据里
79     NSKeyedUnarchiver *Unarchiver=[[NSKeyedUnarchiver alloc] initForReadingWithData:data];
80     //创建一个新的集合存解档集合的数据
81     NSArray *newarr=[Unarchiver decodeObjectForKey:@"arr"];
82     //创建一个新的字符串存解档字符串的数据
83    NSString *newstr=[Unarchiver decodeObjectForKey:@"str"];
84     NSLog(@"%@,%@",newarr,newstr);
85     
86 }
原文地址:https://www.cnblogs.com/tmf-4838/p/5302889.html