iOS歸檔與解歸檔,持久化儲存
點此下載iOS歸檔,持久化儲存,解歸檔詳細工程
//資料持久化的本質:將資料讀取成檔案儲存在本地. 沙箱機制就是系統針對於每一個程式在本地產生的檔案夾(名字隨機產生), 對於不同的應用程式, 不能訪問其他應用程式沙箱內的內容, 對於該應用程式內容起到保護作用:1 Documents:用來儲存長久儲存的資料 2 xxx.app:應用程式的包, 包含應用程式載入所需的所有資源(readonly唯讀, 不可修改), 平時使用的NSBundle就是該包 3 Library: 1) Caches:本機快取, 儲存想暫時儲存的資料(Videos, Musics, Images) 比如:下載的視頻, 音頻, 圖片都儲存在該檔案夾下 2) Preferences:儲存使用者的喜好設定, 比如程式是否是第一次啟動 4 tmp:儲存還未下載完的視頻, 音頻, 當下載完後, 將檔案轉移到Caches檔案夾下#import "WYLReadAndWriteViewController.h"#import "WYLArchive.h"@interface WYLReadAndWriteViewController ()@end@implementation WYLReadAndWriteViewController- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{ self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self;}- (void)viewDidLoad{ [super viewDidLoad]; // Do any additional setup after loading the view. self.view.backgroundColor = [UIColor whiteColor]; self.navigationItem.title = @"檔案讀寫"; UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(40, 84, 220, 40)]; textField.tag = 100; textField.placeholder = @"請輸入內容"; textField.delegate = self; textField.borderStyle = UITextBorderStyleRoundedRect; [self.view addSubview:textField]; [textField release]; UITextField *textField2 = [[UITextField alloc]initWithFrame:CGRectMake(40, 174, 220, 40)]; textField2.tag = 101; textField2.placeholder = @"顯示上一個輸入框的內容"; textField2.delegate = self; textField2.borderStyle = UITextBorderStyleRoundedRect; [self.view addSubview:textField2]; [textField2 release]; UIButton *writeButton = [UIButton buttonWithType:UIButtonTypeSystem]; writeButton.frame = CGRectMake(45, 260, 60, 30); [writeButton setTitle:@"寫入" forState:UIControlStateNormal]; [writeButton addTarget:self action:@selector(write:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:writeButton]; UIButton *readButton = [UIButton buttonWithType:UIButtonTypeSystem]; readButton.frame = CGRectMake(190, 260, 60, 30); [readButton setTitle:@"讀取" forState:UIControlStateNormal]; [readButton addTarget:self action:@selector(read:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:readButton]; UIButton *push = [UIButton buttonWithType:UIButtonTypeSystem]; push.frame = CGRectMake(120, 310, 60, 30); [push setTitle:@"push" forState:UIControlStateNormal]; [push addTarget:self action:@selector(push:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:push]; }- (NSString *)getFilePath{ //用來擷取指定檔案夾的路徑:<#NSSearchPathDirectory directory#>:指定的檔案夾;<#NSSearchPathDomainMask domainMask#>:設定尋找的域, 我們自己的檔案都是儲存在永華域的;<#BOOL expandTilde#>:是否使用詳細路徑(絕對路徑) 因為最初該方法是使用與MAC OS下的, 而對於電腦系統來說, 可能會儲存多個使用者, 所以擷取到得使用者可能有多個, 所以傳回值類型是數組, 但是對於iOS下, 就要只有一個使用者, 所以數組中只有一個元素 /* NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; //2)拼接上要隱藏檔的路徑 NSString *newFilePath = [documentsPath stringByAppendingPathComponent:@"aa.txt"]; NSLog(@"%@", newFilePath); */ NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; NSString *newPath = [filePath stringByAppendingPathComponent:@"test.txt"]; NSLog(@"%@", newPath); return newPath;}- (void)read:(UIButton *)button{ //每次寫入都會將之前的內容覆蓋掉, 若想保留之前的資料, 需要講之前的資料讀出, 然後將要儲存的資料拼接在一起, 一起存入 /* NSString *newFilePath = [self getFilePath]; NSError *error = nil; NSString *content = [NSString stringWithContentsOfFile:newFilePath encoding:NSUTF8StringEncoding error:&error]; UITextField *tf = (UITextField *)[self.view viewWithTag:101]; tf.text = content; */ //字串從本地讀取 /* NSString *filePath = [self getFilePath]; NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil]; UITextField *tf = (UITextField *)[self.view viewWithTag:101]; tf.text = content; */ //數組從本地檔案讀取 NSString *filePath = [self getFilePath];// NSArray *arr = [NSArray arrayWithContentsOfFile:filePath]; //從字典從本地讀取 NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:filePath]; UITextField *tf = (UITextField *)[self.view viewWithTag:100]; UITextField *tf1 = (UITextField *)[self.view viewWithTag:101]; tf.text = dic[@"tf2"]; tf1.text = dic[@"tf1"]; }//檔案讀寫暫時只支援:NSString, NSArray, NSDictionary, NSData, 以及他們的子類.寫入檔案:writeToFile:(這是對象調用的方法), 讀取檔案:每一個類內建的能夠根據路徑建立對象的方法:[類名 類WithContentsOfFile]; 字串:[NSString stringWithContentsOfFile], 數組:[NSArray arrayWithContentsOfFile], 字典:[NSDictionary dictionaryWithContentsOfFile], 二進位流:[NSData dataWithContentsOfFile],(牢牢謹記:對於數組, 字典這樣的容器類, 內部的成員也必須是能夠實現檔案讀寫的八大類之一)- (void)write:(UIButton *)button{ //寫入時, 將第一個輸入框中的文字, 寫入到本地檔案 //1 擷取儲存的內容 UITextField *tf = (UITextField *)[self.view viewWithTag:100]; NSString *content = tf.text; //2 擷取到所要儲存的檔案路徑 //1)擷取Documents檔案夾路徑 NSString *newFilePath = [self getFilePath]; //3 將內容儲存到指定檔案路徑// NSError *error = nil; //字串寫入本地檔案// BOOL isSucceed = [content writeToFile:newFilePath atomically:YES encoding:NSUTF8StringEncoding error:&error]; //數組寫入本地檔案 UITextField *tf2 = (UITextField *)[self.view viewWithTag:101]; NSString *content1 = tf2.text;// NSArray *arr = @[content, content1];// BOOL isSucceed = [arr writeToFile:newFilePath atomically:YES]; //字典寫入本地檔案 NSDictionary *dic = @{@"tf1": content, @"tf2": content1}; BOOL isSucceed = [dic writeToFile:newFilePath atomically:YES]; NSLog(@"%d", isSucceed); }- (void)push:(UIButton *)button{ WYLArchive *archivieVC = [[WYLArchive alloc]init]; [self.navigationController pushViewController:archivieVC animated:YES];}- (BOOL)textFieldShouldReturn:(UITextField *)textField{ [textField resignFirstResponder]; return YES;}- (void)didReceiveMemoryWarning{ [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}/*#pragma mark - Navigation// In a storyboard-based application, you will often want to do a little preparation before navigation- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller.}*/@end#import "WYLArchive.h"#import "Person.h"@interface WYLArchive ()@end@implementation WYLArchive- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{ self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self;}- (void)viewDidLoad{ [super viewDidLoad]; // Do any additional setup after loading the view. self.view.backgroundColor = [UIColor whiteColor]; self.navigationItem.title = @"歸檔與反歸檔"; UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(40, 84, 220, 40)]; textField.tag = 100; textField.placeholder = @"請輸入內容"; textField.borderStyle = UITextBorderStyleRoundedRect; textField.delegate = self; [self.view addSubview:textField]; [textField release]; UITextField *textField2 = [[UITextField alloc]initWithFrame:CGRectMake(40, 174, 220, 40)]; textField2.tag = 101; textField2.placeholder = @"顯示上一個輸入框的內容"; textField2.borderStyle = UITextBorderStyleRoundedRect; textField2.delegate = self; [self.view addSubview:textField2]; [textField2 release]; UIButton *fileButton = [UIButton buttonWithType:UIButtonTypeSystem]; fileButton.frame = CGRectMake(45, 260, 60, 30); [fileButton setTitle:@"歸檔" forState:UIControlStateNormal]; [fileButton addTarget:self action:@selector(file:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:fileButton]; UIButton *archiveButton = [UIButton buttonWithType:UIButtonTypeSystem]; archiveButton.frame = CGRectMake(190, 260, 60, 30); [archiveButton setTitle:@"反歸檔" forState:UIControlStateNormal]; [archiveButton addTarget:self action:@selector(archive:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:archiveButton];}- (NSString *)getPath{ //獲得檔案夾的路徑 /* NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; NSString *newPath = [filePath stringByAppendingPathComponent:@"archive"]; return newPath; */ NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; NSString *newPath = [path stringByAppendingPathComponent:@"archiver"]; return newPath;}- (void)file:(UIButton *)button{ //擷取輸入框的內容 UITextField *tf1 = (UITextField *)[self.view viewWithTag:100]; UITextField *tf2 = (UITextField *)[self.view viewWithTag:101]; /* //封裝成Person對象 Person *person = [[Person alloc] initWithName:tf1.text gender:tf2.text age:18]; //1 建立歸檔對象 NSMutableData *data = [NSMutableData data]; NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; //2 歸檔 [archiver encodeObject:person forKey:@"person"]; [person release]; //3 結束歸檔, 當結束歸檔之後, 再歸檔無效 [archiver finishEncoding]; [archiver release]; //4 data寫入檔案 [data writeToFile:[self getPath] atomically:YES]; */ Person *person = [[Person alloc] initWithName:tf1.text gender:tf2.text age:18]; NSMutableData *data = [NSMutableData data]; NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; [archiver encodeObject:person forKey:@"archiver"]; [person release]; [archiver finishEncoding]; [archiver release]; [data writeToFile:[self getPath] atomically:YES];}- (void)archive:(UIButton *)button{ /* //1 初始化NSMutableData對象 NSMutableData *data = [NSMutableData dataWithContentsOfFile:[self getPath]]; //2 建立一個反歸檔對象 NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data]; //3 反歸檔 Person *person = [unarchiver decodeObjectForKey:@"person"]; //4 結束反歸檔 [unarchiver finishDecoding]; [unarchiver release]; */ NSMutableData *data = [NSMutableData dataWithContentsOfFile:[self getPath]]; NSKeyedUnarchiver *unarchive = [[NSKeyedUnarchiver alloc] initForReadingWithData:data]; Person *person = [unarchive decodeObjectForKey:@"archiver"]; [unarchive finishDecoding]; [unarchive release]; UITextField *tf1 = (UITextField *)[self.view viewWithTag:100]; UITextField *tf2 = (UITextField *)[self.view viewWithTag:101]; tf1.text = person.gender; tf2.text = person.name;}- (BOOL)textFieldShouldReturn:(UITextField *)textField{ [textField resignFirstResponder]; return YES;}- (void)didReceiveMemoryWarning{ [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}/*#pragma mark - Navigation// In a storyboard-based application, you will often want to do a little preparation before navigation- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller.}*/@end