點此下載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