Plist文件的创建与读写
Plist文件(属性列表·Property List)是一种轻量级的存储文件,是使用XML格式以键值对方式进行存储的列表,通常用于用户设置或一些简单的数据存储。
Plist文件的创建方式有两种:①Xcode中创建Plist文件 ②使用代码创建沙盒路径
①Xcode中创建Plist文件
快捷键Command+N -> Resource -> Property List 创建Plist文件(如图):
创建之后,可以添加相应属性(一般为不可修改的数据)。
②使用代码创建沙盒路径
这种方法创建Plist文件,可以进行快速的CRUD(增删改查)操作,也比较容易:
1 #import "ViewController.h" 2 3 @interface ViewController ()<UITextFieldDelegate> 4 5 @property (weak, nonatomic) IBOutlet UITextField *nameField; 6 @property (weak, nonatomic) IBOutlet UITextField *ageField; 7 @property (weak, nonatomic) IBOutlet UITextField *addressField; 8 9 @property(nonatomic,strong)NSString *path; 10 11 @end 12 13 @implementation ViewController 14 15 - (void)viewDidLoad { 16 [super viewDidLoad]; 17 18 self.nameField.delegate = self; 19 self.ageField.delegate = self; 20 self.addressField.delegate = self; 21 22 self.path = [self createPlist]; 23 } 24 25 26 - (NSString*)createPlist{ 27 // 创建Plist文件路径 28 NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; 29 NSString *plistPath = [path stringByAppendingPathComponent:@"temp.plist"]; 30 31 // 创建文件夹管理者 32 NSFileManager *manager = [[NSFileManager alloc] init]; 33 34 // 判断:如若未创建Plist则创建,反之不执行 35 if(![manager fileExistsAtPath:plistPath]) 36 [manager createFileAtPath:plistPath contents:nil attributes:nil]; 37 38 return plistPath; 39 } 40 41 // Plist文件属性设置 42 - (IBAction)saveAction:(id)sender { 43 [self keyboardQuit]; 44 NSDictionary *dict = @{@"name":self.nameField.text, 45 @"age":self.ageField.text, 46 @"address":self.addressField.text}; 47 [dict writeToFile:self.path atomically:YES]; 48 } 49 50 // 控制台查看 51 - (IBAction)showAction:(id)sender { 52 [self keyboardQuit]; 53 NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:self.path]; 54 NSLog(@"NAME:%@", dict[@"name"]); 55 NSLog(@"AGE :%@", dict[@"age"]); 56 NSLog(@"ADDRESS:%@", dict[@"address"]); 57 } 58 59 #pragma mark - keyboard quit: click return 键盘回收 60 - (BOOL)textFieldShouldReturn:(UITextField *)textField{ 61 [self keyboardQuit]; 62 return YES; 63 } 64 65 #pragma mark - keyboard quit: click view 键盘回收 66 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ 67 [self keyboardQuit]; 68 } 69 70 // 取消第一响应者 71 - (void)keyboardQuit{ 72 [self.nameField resignFirstResponder]; 73 [self.ageField resignFirstResponder]; 74 [self.addressField resignFirstResponder]; 75 } 76 77 - (void)didReceiveMemoryWarning { 78 [super didReceiveMemoryWarning]; 79 // Dispose of any resources that can be recreated. 80 } 81 82 @end
我们在Document文件夹中可以查看到已经创建完成Plist文件,之后对Plist文件进行属性设置(写入数据):
再次查看Plist文件,数据已经写入: