數據持久化以及沙盒路徑

什麼是沙盒機制數組

簡單對象寫入文件
NSFileManager
複雜對象寫入文件
 
數據持久化
什麼是數據持久化?
數據的永久存儲
爲何要作數據持久化?:存儲在內存中的數據,程序關閉,內存釋放,數據丟失,這種數據是臨時的,用戶下次打開應用程序,還要從新聯網去刷新數據,無疑增長了用戶的負擔
數據持久化的本質:數據保存成文件,存儲到程序的沙盒中
 
什麼是沙盒機制?
每一個應用程序位於文件系統的嚴格限制部分
每一個應用程序只能在爲該程序建立的文件系統中讀取文件
每一個應用程序在iOS系統內部都放在了統一的文件夾目錄下面
沙盒的本質就是一個文件夾,名字是隨機分配的
 
沙盒路徑的位置
1.經過Finder查找程序的沙盒相對路徑
~/Library/Application Support/iPhone Simulator
 
常見問題
模擬器路徑內有可能包含多個系統版本的路徑
 
沙盒機制
經過代碼查找程序沙盒相對路徑
NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory directory, NSSearchPathDomainMask domainMask domainMask, BOOL expandTilde)
 
獲取沙盒目錄路徑的方法
NSHomeDirectory----------------------->沙盒主路徑
NSDocumentDirectory------------------>Documents文件夾
NSLibraryDirectory---------------------->Library文件夾
NSCachesDirectory---------------------->Caches文件夾
NSTemporaryDirectory()---------------->tmp文件夾
 
NSBundle
每一個應用程序文件夾內的app文件是什麼?
每一個應用程序文件夾內的app文件路徑如何獲取?
 
獲取應用程序app文件夾內的文件路徑
獲取應用程序的相關配置屬性
 
2、簡單對象寫入文件

// 字符串對象寫入文件安全

    // 獲取沙盒目錄app

    NSString *documentsPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES).lastObject;dom

    NSLog(@"%@", documentsPath);工具

    // 方法二編碼

    NSString *homePath = NSHomeDirectory();atom

    // homePath = [homePath stringByAppendingString:@"/Documents"];spa

    homePath = [homePathstringByAppendingPathComponent:@"Documents"];代理

    NSLog(@"%@", homePath);code

    

    // 2.拼接文件路徑

    NSString *filePath = [documentsPathstringByAppendingPathComponent:@"abc.txt"];

    NSLog(@"%@", filePath);

    

    NSString *str = @"情人節了,賽賽你仍是一我的嗎?";

    // 將str中的字符串寫入文件

     [str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncodingerror:nil];

    // 上面三行已經實現了把數據存入abc.txt文件夾下,實現數據持久化

    NSString *str2 = [NSString stringWithContentsOfFile:filePathencoding:NSUTF8StringEncoding error:nil];

    NSLog(@"%@", str2);

    

    // 數組對象寫入文件

    // 在文件夾後面拼接數組txt文件,實現數組的添加

    NSString *arrayFilePath = [documentsPathstringByAppendingPathComponent:@"array.txt"];

    NSArray *array = @[@"大賽賽", @"大鼠標", @"小超超", @"小彪彪", @"大黃黃",@"大波波"];

    [array writeToFile:arrayFilePath atomically:YES];

    

    NSArray *array2 = [NSArray arrayWithContentsOfFile:arrayFilePath];

    NSLog(@"%@", array2);

    

    

    // 字典對象寫入文件

    // 在文件夾後面拼接字典txt文件,實現字典的添加

    NSString *dictionaryFilePath = [documentsPathstringByAppendingPathComponent:@"dictionary.txt"];

    NSDictionary *dictionary = @{@"saisai": @"賽賽",

                                 @"chaochao":@"超超",

                                 @"doudou":@"豆豆"};

    [dictionary writeToFile:dictionaryFilePath atomically:YES];

    

    NSDictionary *dictionary2 = [NSDictionarydictionaryWithContentsOfFile:dictionaryFilePath];

    NSLog(@"%@", dictionary2);

    

    // 圖片對象寫入文件

    // 將圖片資源轉爲NSData類型,再儲存

     UIImage *image = [UIImage imageNamed:@"1.png"];

    // 將圖片轉化爲NSData

    NSData *imageData = UIImagePNGRepresentation(image);

    

    // 拼接data數據路徑

    NSString *dataFilePath = [documentsPathstringByAppendingPathComponent:@"image.txt"];

    // 將data數據寫入文件中

    [imageData writeToFile:dataFilePath atomically:YES];

 

3、NSFileManager

NSFileManager, 文件管理,使用detaultManager, 建立單例對象。

能夠建立文件夾

能夠建立、移動、複製、刪除文件

能夠判斷文件是否存在

//NSFileManager

    NSString *path1 = [documentsPathstringByAppendingPathComponent:@"path1/path2/path3"];

    NSLog(@"%@", path1);

    

    // 建立文件夾

    [[NSFileManager defaultManager] createDirectoryAtPath:path1withIntermediateDirectories:YES attributes:nil error:nil];

    

    // 判斷文件是否存在

    BOOL b = [[NSFileManager defaultManager]fileExistsAtPath:dictionaryFilePath];

 

    NSLog(@"%d", b);

 

4、複雜對象寫入文件

#import 

 

 

// 首先建立一個Person類,遵照NSCoding協議,在.m文件中實現編碼和反編碼的方法

@interface Person : NSObject<</span>NSCoding>

 

 

@property (nonatomic, copy) NSString *name;

@property (nonatomic, copy) NSString *gender;

@property (nonatomic, assign) NSInteger age;

 

@end

.m文件

#import "Person.h"

 

#define kName @"name"

#define kGender @"gender"

#define kAge @"age"

 

@implementation Person

 

#pragma mark 進行編碼

- (void)encodeWithCoder:(NSCoder *)aCoder

{

    [aCoder encodeObject:self.name forKey:kName];

    [aCoder encodeObject:self.gender forKey:kGender];

    // 幾個屬性就要寫幾行,對於NSInteger類型的有專用的方法

    [aCoder encodeInteger:self.age forKey:kAge];

}

 

#pragma mark 反編碼

- (id)initWithCoder:(NSCoder *)aDecoder

{

    self = [super init];

    if (self) {

        self.name = [aDecoder decodeObjectForKey:kName];

        self.gender = [aDecoder decodeObjectForKey:kGender];

        self.age = [aDecoder decodeIntegerForKey:kAge];

    }

    return self;

}

#pragma mark dealloc

- (void)dealloc

{

    [_name release], _name = nil ;// 安全釋放

    [_gender release], _gender = nil; // 安全釋放

    [super dealloc];

}

 

@end

 

在主控制器中引入Person類對象

#import "JYFViewController.h"

#import "Person.h"

 
下面便是方法

// 建立Person對象

    Person *person = [[Person alloc] init];

    person.name = @"彪彪";

    person.gender = @"男";

    person.age = 22;

 

// 建立可變的NSMutableData準備存放person對象

 

    NSMutableData *personData = [NSMutableData data];

 

// 建立歸檔工具

 

    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:personData];

 

// 進行二進制的轉換

    [archiver encodeObject:person forKey:@"personKey"];

 

// 完成轉換

    [archiver finishEncoding];

 

// 建立路徑

 

    NSString *personFilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES).lastObjectstringByAppendingPathComponent:@"person.abc"];

 

// 進行NSData對象的寫入

 

    //[personData writeToFile:personFilePath atomically:YES];

 

// 反歸檔

    // 1.建立一個data用來接受person文件路徑中的數據

    NSData *data = [NSData dataWithContentsOfFile:personFilePath];

 

// 2.使用data去建立反歸檔工具

 

    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];

 

// 3.使用工具把二進制數據轉回複雜對象

    Person *p = [unarchiver decodeObjectForKey:@"personKey"];

 

 // 4.結束反歸檔

 

    [unarchiver finishDecoding];

 

// 簡便方法

    // 建立路徑

    NSString *chaochoaFilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES).lastObjectstringByAppendingPathComponent:@"chaochao.avi"];

    NSLog(@"%@", chaochoaFilePath);

    

    // 建立對象

    Person *chaochao = [[Person alloc] init];

    chaochao.name = @"超超";

    chaochao.gender = @"男";

    chaochao.age = 23;

    

    // 進行數據保存

    [NSKeyedArchiver archiveRootObject:chaochao toFile:chaochoaFilePath];

    

    // 讀取

    Person *chaochaoPerson = [NSKeyedUnarchiverunarchiveObjectWithFile:chaochoaFilePath];

 

    NSLog(@"%@ %@ %d", chaochaoPerson.name, chaochaoPerson.gender, chaochao.age);

 

總結:

沙盒機制

簡單對象寫入文件,只能是NSString、NSArray、NSDictionary、NSData

複雜對象寫入文件,遵照NSCoding協議,實現代理方法

相關文章
相關標籤/搜索