plist文件是在ios開發中經常會用到的,用來存儲一些少量的數據,例如手機設備信息,用戶基本信息什么的,不過大量的信息還是用數據庫。像這種登錄保存密碼就是把信息寫入plist文件。
以下是效果圖
首先同學們要先搞兩張圖片,一張帶鈎鈎的小方框,一張不帶鈎的小方框,用以顯示密碼是否保存的兩種狀態。大家如果沒有的話,就從上面的圖片截取吧。
建議大家WithOUt IB
程序不大,就寫在一個類里面了先來看看.h文件
#import <UIKit/UIKit.h> @interface ViewController : UIViewController<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource> { BOOL recordPwd; UITextField *nameTextField; UITextField *pswTextField; } @property (retain,nonatomic)UIImageView *recordBtn; @property (retain,nonatomic)NSMutableArray *cellRightArray; - (void)readUserInfoFromFile; - (void)recoredBtnClick; - (void)writePasswordToFile; @end
再來看看.m文件:
// // ViewController.m // plistTest // // Created by changjian on 12-12-3. // Copyright (c) 2012年 __MyCompanyName__. All rights reserved. // #import "ViewController.h" #define USERNAME @"nameTextField" #define PASSWORD @"pswTextField" @implementation ViewController @synthesize recordBtn; @synthesize cellRightArray; - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } #pragma mark - View lifecycle - (void)viewDidLoad { [super viewDidLoad]; cellRightArray = [[NSMutableArray alloc]init];//作為屬性變量的數組如果不初始化是不能用的,這個數組用來保存UITextFiled中的用戶名和密碼。 recordPwd = NO;//剛開始把是否保存密碼設置為NO UITableView *table = [[UITableView alloc]initWithFrame:CGRectMake(10, 20, 300, 100) style:UITableViewStyleGrouped]; table.delegate = self; table.dataSource = self; table.backgroundColor = [UIColor whiteColor]; [self.view setBackgroundColor:[UIColor whiteColor]]; recordBtn = [[UIImageView alloc]init];//這個就是那個帶鈎的小框框,之前嘗試用UIButton,但是不好切換button的backgroundView,所以就換了UIImageView,給它添加手勢。 recordBtn.frame = CGRectMake(180, 130, 40, 40); recordBtn.userInteractionEnabled = YES; UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(110, 130, 100, 40)]; label.text = @"記住密碼"; [self.view addSubview:label]; [label release]; UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(recoredBtnClick)];//添加了一個手勢,單擊觸發事件 tapGesture.numberOfTapsRequired = 1;//點擊一下 [recordBtn addGestureRecognizer:tapGesture];這里注意是在UIImageView上添加手勢 [self readUserInfoFromFile];//在圖片初始化之前先讀取plist文件,判斷recordPwd if (recordPwd) { recordBtn.image = [UIImage imageNamed:@"check_on@2x.png"]; } else{ recordBtn.image = [UIImage imageNamed:@"check_off@2x.png"]; } [self.view addSubview:table]; [self.view addSubview:recordBtn]; [tapGesture release]; [table release]; } - (void)viewDidUnload { [super viewDidUnload]; self.recordBtn = nil; self.cellRightArray = nil; } - (void)readUserInfoFromFile//從plist讀取數據 { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
//以上的三句話獲取沙盒中data.plist的路徑。 NSLog(@"文件路徑:%@",path); NSMutableDictionary *saveStock = [[NSMutableDictionary alloc]initWithContentsOfFile:path];//從該路徑讀取文件,注意這里是讀取,跟創建plist的init方法不同,看下面就知道了 recordPwd = [[saveStock objectForKey:@"recordPwd"]boolValue];//@"recordPwd"是一個key,存到字典何從字典中取值都要用到 if (!recordPwd) { nameTextField.text = @""; pswTextField.text = @""; [saveStock removeAllObjects];//移除字典內所有元素 } else{ nameTextField.text = [saveStock objectForKey:USERNAME]; pswTextField.text = [saveStock objectForKey:PASSWORD]; [pswTextField setSecureTextEntry:YES];//密碼設置為暗文 } NSLog(@"nameTextField.text==%@,pswTextField.text=%@",nameTextField.text,pswTextField.text); NSLog(@"讀取saveStock=%@",saveStock); [saveStock release]; } //把是否記住密碼信息寫進data.plist文件 - (void)writePasswordToFile { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"]; NSLog(@"filePath:%@",path); NSMutableDictionary *data = [[NSMutableDictionary alloc]init];//字典初始化,注意這里的init方法,跟-(void)readUserInfoFromFile方法中的字典初始化方法不同。
NSLog(@"self.cellRightArray=%@",self.cellRightArray); if (nameTextField.text.length != 0||pswTextField.text.length != 0) {//如果輸入不為空 [data setObject:nameTextField.text forKey:USERNAME];//用戶名和密碼存入字典,這里的key用了宏定義,其實@"recordPwd"也可以用,在文中多次使用比較省事 [data setObject:pswTextField.text forKey:PASSWORD]; } [data setObject:[NSNumber numberWithBool:recordPwd] forKey:@"recordPwd"]; [data writeToFile:path atomically:YES]; NSLog(@"是否記住密碼信息==%@",data); [data release]; } - (void)recoredBtnClick//點擊是否記住密碼 { UIImage *image = [[UIImage alloc]init]; if (recordPwd) { recordBtn.image = [UIImage imageNamed:@"check_off@2x.png"]; recordPwd = NO; } else{ recordBtn.image = [UIImage imageNamed:@"check_on@2x.png"]; recordPwd = YES; } [self writePasswordToFile]; [image release]; } #pragma mark -tableView代理方法實現- - (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSArray *left = [NSArray arrayWithObjects:@"姓名:",@"密碼:", nil]; NSArray *right = [NSArray arrayWithObjects:@"請輸入用戶名",@"請輸入密碼", nil]; static NSString *cellIdentifier = @"cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]autorelease]; cell.selectionStyle = UITableViewCellSelectionStyleNone; UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 8, 80, 30)]; label.text = [NSString stringWithFormat:[left objectAtIndex:indexPath.row]]; label.backgroundColor = [UIColor clearColor]; [cell.contentView addSubview:label]; [label release]; if (indexPath.row == 0 ){ nameTextField = [[[UITextField alloc]initWithFrame:CGRectMake(90, 10, 140, 30)]autorelease]; nameTextField.placeholder = [NSString stringWithFormat:[right objectAtIndex:indexPath.row]]; nameTextField.delegate = self; [cell.contentView addSubview:nameTextField]; }else{ pswTextField = [[[UITextField alloc]initWithFrame:CGRectMake(90, 10, 140, 30)]autorelease]; pswTextField.placeholder = [NSString stringWithFormat:[right objectAtIndex:indexPath.row]]; pswTextField.delegate = self; [pswTextField setSecureTextEntry:YES]; [cell.contentView addSubview:pswTextField];//本人智商不夠,所以才去這種笨寫法,不知道有沒高手能用循環創建來寫? [self readUserInfoFromFile];//還要再讀取一次,如果注銷會發生什么?大家可以去試試 } } return cell; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 2; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event//點擊空白處隱藏鍵盤 { [nameTextField resignFirstResponder]; [pswTextField resignFirstResponder]; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; } - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); } - (void)dealloc { [cellRightArray release]; [nameTextField release]; [pswTextField release]; [recordBtn release]; [super dealloc]; } @end
完成了,但是工作還沒玩呢。先去忙了,大家如果有問題給我留言啊!