先上幾個圖片解釋一下什麼是沙盒
然後是簡單對象的數據持久化,複雜對象數據持久化,要繼承一個協議
NSCopying,重寫裏面的兩個方法。
- (void)encodeWithCoder:(NSCoder *)aCoder;
- (id)initWithCoder:(NSCoder *)aDecoder; // NS_DESIGNATED_INITIALIZER
下面直接上代碼
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
#pragma mark -------------獲取沙盒下的文件目錄
//1.獲取沙盒中Documents這個文件夾得路徑
//第一種方式
NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES).lastObject;
NSLog(@"%@",documentsPath);
//第二種方式
NSString *user = NSHomeDirectory();
NSString *documentPath1 = [user stringByAppendingPathComponent:@"Documents"];
NSLog(@"%@",documentPath1);
//獲取應用程序包
NSLog(@"%@",[NSBundle mainBundle].resourcePath);
#pragma mark------------簡單對象持久化
NSString *string = @"I love you so much";
//1.存儲路徑
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"string.txt"];
//2.將字符串寫入文件
[string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
//3.讀取文件中的字符串
NSString *str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@",str);
//4.將數組寫入未見
#warning mark ------------如果想把數組array直接寫入文件,數組中的文件必須是簡單對象(NSString,NSArray)
//1.拼接存儲路徑
NSString *arrPath = [documentsPath stringByAppendingPathComponent:@"array.txt"];
NSArray *arr = @[@"a",@"b",@"c"];
//2.寫入文件
[arr writeToFile:arrPath atomically:YES];
//3.從文件中讀取數組
NSArray *array = [NSArray arrayWithContentsOfFile:arrPath];
NSLog(@"%@",array);
//將字典持久化
NSDictionary *dic = @{@"name":@"張三",@"age":@"19",@"sex":@"男"};
NSString *dicPath = [documentsPath stringByAppendingPathComponent:@"dictionary.txt"];
[dic writeToFile:dicPath atomically:YES];
NSLog(@"%@",dicPath);
NSDictionary *testDic = [NSDictionary dictionaryWithContentsOfFile:dicPath];
for (NSString *key in testDic) {
NSLog(@"%@",[testDic objectForKey:key]);
}
//將NSData數據持久化
UIImage *image = [UIImage imageNamed:@"1.jpg"];
NSData *data = UIImageJPEGRepresentation(image, 1.0);
//存儲數據
NSString *dataPath = [documentsPath stringByAppendingPathComponent:@"data.txt"];
[data writeToFile:dataPath atomically:YES];
#pragma mark ----------NSFileManager(文件管理類)
//獲取緩存文件夾所在路徑
NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
NSDictionary *dic1 = @{@"name":@"李四"};
//在cachesPath路徑下創建一個文件夾
NSString *directoryPath = [cachesPath stringByAppendingPathComponent:@"path"];
//創建一個文件管理器對象
NSFileManager *fielMager = [NSFileManager defaultManager];
//根據路徑創建文件夾
NSDictionary *fileData = @{@"createTime":@"2015-9-9"};
[fielMager createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:fileData error:nil];
//拼接存儲路徑,存到文件中,而不是存到文件夾中
NSString *dicPath1 = [directoryPath stringByAppendingPathComponent:@"dic.jpg"];
[dic1 writeToFile:dicPath1 atomically:YES];
//創建文件,這個方法存儲的數據是NSData
[fielMager createFileAtPath:dicPath1 contents:data attributes:fileData];
//刪除指定的文件,先判斷給定的文件路徑是否真實存在
if ([fielMager fileExistsAtPath:dicPath1]) {
NSLog(@"%d",[fielMager fileExistsAtPath:dicPath1]);
[fielMager removeItemAtPath:dicPath1 error:nil];
}
#pragma mark -------------NSUserDefaults 也是單例類
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:@"yaxin" forKey:@"name"];
[defaults setValue:@"123" forKey:@"password"];
//立即同步到文件中
[defaults synchronize];
NSString *name = [defaults valueForKey:@"name"];
NSString *pwd = [defaults valueForKey:@"password"];
NSLog(@"%@, %@",name,pwd);
#pragma mark ------------複雜對象持久化
//過程:(複雜對象->歸檔->NSData->writeToFile)
Person *person = [[Person alloc]init];
person.name = @"張三";
person.gender = @"男";
person.age = 23;
NSMutableData *mutData = [NSMutableData data];
//創建歸檔器
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:mutData];
//進行歸檔
[archiver encodeObject:person forKey:@"person"];
//結束歸檔
[archiver finishEncoding];
//將歸檔之後的NSData數據,寫入文件
//①存儲路徑
NSString *personPath = [cachesPath stringByAppendingPathComponent:@"person.txt"];
//②寫入文件
[mutData writeToFile:personPath atomically:YES];
NSLog(@"%@",mutData);
#pragma mark --------------反歸檔(讀取複雜對象)
//過程:(讀取文件->NSData - >反歸檔-》複雜對象那個)
//從文件中讀取NSData數據
NSData *personData = [NSData dataWithContentsOfFile:personPath];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:personData];
//使用反歸檔工具對resultData數據進行反歸檔
Person *person1 = [unarchiver decodeObjectForKey:@"person"];
//結束反歸檔
[unarchiver finishDecoding];
NSLog(@"%@,%@,%lu",person1.name,person1.gender,person1.age);
// Do any additional setup after loading the view, typically from a nib.
}
對於複雜對象
#import <Foundation/Foundation.h>
//複雜對象歸檔第一步:遵守NSCoding協議
@class Dog;
@interface Person : NSObject<NSCopying>
@property(nonatomic,retain)NSString * name;
@property(nonatomic,retain)NSString * gender;
@property(nonatomic,assign)NSInteger age;
@property(nonatomic,retain)Dog * dog;
@end
#import "Person.h"
@implementation Person
#pragma mark ===========進行編碼
- (void)encodeWithCoder:(NSCoder *)aCoder //aCoder就是編碼器
{
//編碼
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeObject:self.gender forKey:@"gender"];
[aCoder encodeInteger:self.age forKey:@"age"];
// [aCoder encodeObject:self.dog forKey:@"dog"]; //在dog的那邊也要歸檔
}
#pragma mark --------------進行反編碼
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.gender = [aDecoder decodeObjectForKey:@"gender"];
self.age = [aDecoder decodeIntegerForKey:@"age" ];
// self.dog = [aDecoder decodeObjectForKey:@"dog"]; //在dog的那邊也要反歸檔
}
return self;
}
@end