1. IOS數據存儲:
什麼是沙盒: 與其他文件系統隔離,應用必須待在自己的沙河裏面,不能互相訪問
bundle 和 沙盒是分開的
*沙盒路徑:
Documents :比較貴重數據,Itunes 會設備的時候會備份改目錄
Library/Caches : 不會備份,存儲體積大
Library/Preference: 保存偏好設置, 系統管理,會備份
tmp: 臨時數據,不會備份,引用沒有運行時候,系統可能清除該目錄
*bundle路徑:
xx.app
*Sqlite3 數據存儲, Core Data: 對sqlite封裝,面向對象
2. 數據存儲Api:
// 獲取Bundle 路徑
NSString* path= [NSBundle mainBundle].bundlePath;
NSLog(@"path=%@",path);
// 獲取 Documents 文件夾
//1. 獲取沙盒路徑
NSString* homeDir= NSHomeDirectory();
NSLog(@"沙盒:%@",homeDir);
// 2. 拼接字符串(方式1)
NSString* documentPath= [homeDir stringByAppendingString:@"/Documents"];
NSLog(@"documentPath=%@",documentPath);
// 方式2
documentPath= [homeDir stringByAppendingPathComponent:@"Documents"];
NSLog(@"方式2:%@",documentPath);
// 方式3
documentPath = [ NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask , YES) lastObject];
NSLog(@"方式3: %@",documentPath);
// 獲取Libray/Caches 文件夾
NSString* libraryCache= [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSLog(@"librayCache:%@",libraryCache);
//獲取 tmp 文件夾
NSString* tempPath = NSTemporaryDirectory();
NSLog(@"tempPath:%@",tempPath);
// 偏好設置 Library/Preference
// 偏好設置,比如記住密碼, 是否自動登錄功能
NSUserDefaults* userDefault= [NSUserDefaults standardUserDefaults];
// 設置數據
[userDefault setBool:YES forKey:@"isAutologin"];
[userDefault setObject:@"jack" forKey:@"name"];
[userDefault setObject:@"123" forKey:@"pwd"];
// 立即存儲
[userDefault synchronize];
NSLog(@"%@",NSHomeDirectory());
// 讀取偏好設置
BOOL isAutoLogin = [userDefault boolForKey:@"isAutologin"];
NSString* name =[userDefault stringForKey:@"name"];
NSLog(@"%d---%@",isAutoLogin,name);
3. Documents/name.plist數據存儲 , 類似Android Sp存儲
// 數據寫入
NSString* direPath = [NSHomeDirectory() stringByAppendingString:@"/Documents"];
NSString* filePath= [direPath stringByAppendingString:@"/name.plist"];
NSArray* array=@[@"A",@"B",@"C"];
NSLog(@"direPath:%@",filePath);
[array writeToFile:filePath atomically:YES];
// 數據讀取
NSArray* readArray= [NSArray arrayWithContentsOfFile:filePath];
NSLog(@"readArray:%@",readArray);
實體類存儲plist中,歸檔,反歸檔
Person.h
#import "Person.h"
@interface Person()
@end
@implementation Person
// 歸檔 告訴系統要存儲對象的那些屬性
-(void)encodeWithCoder:(NSCoder *)coder{
[coder encodeObject:self.name forKey:@"name"];
}
// 反歸檔, 讀取對象的那些屬性
- (nullable instancetype)initWithCoder:(nonnull NSCoder *)coder {
if(self = [super init]){
self.name = [coder decodeObjectForKey:@"name"];
}
return self;
}
@end
4. 存儲 數據 寫入、讀取:
// 歸檔 存儲數據
NSString* direPath = [NSHomeDirectory() stringByAppendingString:@"/Documents"];
NSString* filePath= [direPath stringByAppendingString:@"/name.plist"];
Person* person= [Person new];
person.name=@"xiaoming";
[NSKeyedArchiver archiveRootObject:person toFile:filePath];
NSLog(@"home:%@",NSHomeDirectory());
//反 歸檔 讀取數據
person = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"person.name:%@",person.name);