//*****************************Plist解析 ***************************** //1.1建立視圖對象
- (void)createButtons
{
NSArray *arr = @[@"讀取Plist檔案",@"寫入Plist檔案"];
for (int i=0; i<2; i++) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom ];
btn.frame = CGRectMake(40, 100+i*200, 300, 40);
btn.titleLabel.font = [UIFont systemFontOfSize:26];
[btn setTitle:arr[i] forState:UIControlStateNormal];
btn.tag = 100+i;
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
self.view.backgroundColor = [UIColor lightGrayColor];
}
//1.2定義按鈕點選事件處理方法
- (void)btnClick:(UIButton *)btn
{
//2讀取Plist檔案
if (btn.tag == 100) {
//2.1.取出PLIST檔案路徑
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"MyList" ofType:@"plist"];
//2.2讀取檔案内容建立字典
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:plistPath];
//2.3取到字典中資料
NSString *userName = [dict objectForKey:@"UserName"];
NSString *passWord = [dict objectForKey:@"Password"];
NSString *nickName = [dict objectForKey:@"NickName"];
//2.3.1周遊子成員數組擷取字典對象
for (NSDictionary *dict in array) {
NSLog(@"dict = %@", dict);
}
NSLog(@"userName:%@",userName);
NSLog(@"passWord:%@",passWord);
NSLog(@"nickName:%@",nickName);
}else{
//3.建立寫入Plist檔案資料
//plist檔案中的根節點隻能是數組或字典,plist檔案中存放的資料隻能
是NSDATA,NSDATE,NSString,NSNumber,Bool,NSArray,NSDictionary
//3.1建構寫入plist中的字典或者數組
NSArray *array = @[@"first",@"second",@"third"];
NSDictionary *dict = [NSDictionary
dictionaryWithObjectsAndKeys:@"one",@"1",@"two",@"2",array,@"array", nil];
//3.2組合字典檔案路徑
NSString *plistPath = [[[NSBundle mainBundle]bundlePath] stringByAppendingString:@"/mydata.plist"];
//3.3寫入plist檔案
BOOL res = [dict writeToFile:plistPath atomically:YES];
if (res) {
NSLog(@"寫入成功");
}else{
NSLog(@"寫入失敗");
}
}
}
//*****************************NSUserDefault檔案解析*****************************
- (void)btnClick:(UIButton *)btn
{
//應用程式的Defaults System
//1.建立(單例方法,取到應用程式中的預設的Defaults System)
NSUserDefaults *df = [NSUserDefaults standardUserDefaults];
if (btn.tag == 101) {
//1.2設定df
[df setObject:@"AAA" forKey:@"KEY_AAA"];
[df setObject:@"BBB" forKey:@"KEY_BBB"];
//1.3同步資料,隻有執行了這行代碼,往df中寫入資料,才會真正的執行
BOOL res = [df synchronize];
if (res) {
NSLog(@"同步寫入成功");
}else{
NSLog(@"同步寫入失敗");
}
}else{
//2讀取
NSString *aaa = [df objectForKey:@"KEY_AAA"];
NSLog(@"%@",aaa);
}
}