淺談iOS的文件操作
一、沙盒路徑
沙盒主路徑:是程序運行期間系統會生成一個專屬的沙盒路徑,應用程序在使用期間非代碼的文件都存儲在當前的文件夾路徑里面我們通過以下代碼可以打印出沙盒主路徑
NSString *homePath =NSHomeDirectory(); NSLog(@'%@',homePath);
我們根據打印出的路徑前往文件夾可以進入包含 Documents Library 和 tmp文件夾的文件夾 這個就是沙盒主路徑

Documents:用來存儲永久性的數據的文件 程序運行時所需要的必要的文件都存儲在這里(數據庫)itunes會自動備份這里面的文件Library:用于保存程序運行期間生成的文件Caches:文件夾用于保存程序運行期間產生的緩存文件Preferences:主要是保存一些用戶偏好設置的信息,一般情況下,我們不直接打開這個文件夾 而是通過NSUserDefaults進行偏好設置的存儲tmp:臨時文件夾---程序運行期間產生的臨時歲騙會保存在這個文件夾中 通常文件下載完之后或者程序退出的灰自動清空此文件夾itunes不會備份這里的數據。 ~~~~tips: 由于系統會清空此文件夾所以下載或者其他臨時文件若需要持久化請及時移走
//第一個參數:要查詢的文件的路徑 //第二個參數:要查詢路徑所屬的用戶 iOS是單用戶 //第三個參數的意思 YES是絕對路徑 NO是相對路徑 //區別于OS-X系統 iOS應用文件夾中通常只有一個文件路徑 由于OC同時支持的蘋果系列產品的開發 在MacOS里面會同時存在很多軟件 通常生成的路徑放在一個數組里面 //iOS端一次只有一個應用 所以取數組唯一的一個元素即可 NSArray *documentArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, NO); NSLog(@'%@',documentArray);//打印的結果是 '~/Documents' NSString *documentPath = [documentArray firstObject]; NSLog(@'documentPath = %@',documentPath);//結果是 ~/Documents 對比以上我們可以打印試著獲取幾個路徑 NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)firstObject]; NSLog(@'libraryPath = %@',libraryPath); NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject]; NSLog(@'ChchesPath = %@',cachesPath); NSString *preferencePath =[libraryPath stringByAppendingString:@'/preferences']; NSLog(@'%@',preferencePath);
另外 在這里值得我們注意的一點是:.app的路徑 iOS 8 之前bundle和tmp等文件統一放在主路徑下(home)---iOS 8 之后boundle放在了container文件夾的下面
二、簡單對象寫入文件1、NSString 寫入文件 讀取//準備字符串 NSString *string = @'I love my iOS teacher'; //2 準備路徑 NSString *path =NSHomeDirectory(); path = [path stringByAppendingString:@'/見哥.txt']; //3 寫入文件 // 3.1第一個參數 路徑 // 3.2第二個參數 是否進行線性操作(YES保證發生意外時有中轉文件來保存信息 直至寫入完成 但是損耗大. NO的時候寫入速度快 但是沒有安全保障) // 3.3第三個參數 編碼方式 // 3.4第四個參數 錯誤對象 [string writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
讀取文件
NSString *contentString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; NSLog(@'%@',contentString);2、NSArray 寫入文件 讀取
NSArray *array = [NSArray arrayWithObjects:@'Lily',@'Yucui',@'Star',@'Ling',@'Wenqi',@'Yangyang', nil]; NSString *docuPath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject]; docuPath =[docuPath stringByAppendingString:@'/Lady.txt']; //寫入文件 [array writeToFile:docuPath atomically:YES]; NSLog(@'docuPath = %@',docuPath); //取出文件 NSArray *array1 = [NSArray arrayWithContentsOfFile:docuPath]; NSLog(@'%@',array1);3、NSDictionary 寫入文件 讀取
類比于以上
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@'SB',@'1',@'38',@'2',@'孩子',@'3', nil]; NSString *prefePath =[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)firstObject]; prefePath = [prefePath stringByAppendingString:@'/preferences/SB.txt']; [dict writeToFile:prefePath atomically:YES]; NSDictionary *dic =[NSDictionary dictionaryWithContentsOfFile:prefePath];4、NSData對象寫入 讀取
我們搞一張圖片 (波多老師喲~) 為例
UIImage *image =[UIImage imageNamed:@'11.jpg']; NSString *homePath =NSHomeDirectory(); homePath = [homePath stringByAppendingString:@'/Sex.jpg']; NSData *data = UIImageJPEGRepresentation(image, 1); [data writeToFile:homePath atomically:YES]; //讀取圖片 UIImageView *aImageView = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds]; aImageView.image = [UIImage imageWithContentsOfFile:homePath]; [self.view addSubview:aImageView];三、復雜對象寫入文件
簡單對象可以通過writeTofile寫入對象 但是復雜對象沒有writeToFile的方法寫入文檔,所以我們需要借助歸檔和反歸檔,將復雜對象轉化成簡單對象,寫入文檔首先, 我們x-code新建一個類 SingleVip 繼承與NSObject 遵守 NSCoding協議
.h #import <Foundation/Foundation.h> @interface SingleVip : NSObject<NSCoding> @property(nonatomic,strong)NSString *name; @property(nonatomic,strong)NSString *assets;//資產 @property(nonatomic,strong)NSString *car; @property(nonatomic,assign)int age; @end .m #import 'SingleVip.h' //定義成宏 方便下面使用 也可以減少出錯 #define kName @'name' #define kAssets @'assets' #define kCar @'car' #define kAge @'age' @implementation SingleVip #pragma mark---NSCoding必須實現的兩個----- //編碼 這個方法就是將對象轉化成data的時候會執行的 - (void)encodeWithCoder:(NSCoder *)aCoder{ [aCoder encodeObject:_name forKey:kName]; [aCoder encodeObject:_assets forKey:kAssets]; [aCoder encodeObject:_car forKey:kCar]; [aCoder encodeInt:_age forKey:kAge];} //反編碼 - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder{ if (self = [super init]) {_name = [aDecoder decodeObjectForKey:kName];_assets = [aDecoder decodeObjectForKey:kAssets];_age= [aDecoder decodeIntForKey:kAge];_car = [aDecoder decodeObjectForKey:kCar]; } return self;} @end
在以上基礎上 我們創建一個SingleVip類的實例變量 進行歸檔和反歸檔的操作 直接上代碼吧、、、往下看
SuperMan *man =[SuperMan new]; man.name = @'見哥'; man.age = 18; man.car = @'鳳凰牌大聯合'; man.assets = @'窮類屌蛋精光'; // //準備路徑 NSString *homePath =NSHomeDirectory(); homePath = [homePath stringByAppendingString:@'/鉆石王老五.txt']; // //創建數據對象 用來存放vip對象 NSMutableData *data =[NSMutableData data]; // //創建歸檔對象 NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data]; // //開始歸檔 [archiver encodeObject:vip forKey:@'vip']; // //完成歸檔 [archiver finishEncoding]; // //寫入文件 [data writeToFile:homePath atomically:YES]; //反歸檔 //將文件里面的data對象讀取出來 NSData *_data = [NSData dataWithContentsOfFile:homePath]; //創建反歸檔對象 NSKeyedUnarchiver *unArchiver =[[NSKeyedUnarchiver alloc]initForReadingWithData:_data]; SingleVip *_vip = [unArchiver decodeObjectForKey:@'vip']; [unArchiver finishDecoding];//完成反歸檔 NSLog(@'%@',_vip.name);
在這里有一點是需要我們區分的,歸檔并不是數據持久化的方式 而是輔助復雜對象轉化成簡單對象的一種方式 其實真正實現數據持久化的仍然是寫入文件writeToFile
iOS常見的數據持久化的方式 主要有以下幾點:// plist (屬性列表)// NSUserDefaults 偏好設置 單例// writeToFile 寫入文件// SQLite 數據庫// CoreData
4、文件操作我們以一張圖片為例
#define K_IMG @'http://news.eastday.com/images/thumbnailimg/month_1511/201511170142052896.jpg' __weak typeof(self)temp = self; NSURLSessionDownloadTask *downLoadTask = [[NSURLSession sharedSession]downloadTaskWithURL:[NSURL URLWithString:K_IMG] completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) { //data對象 NSData *data = [NSData dataWithContentsOfURL:location]; //創建文件管理者對象 NSFileManager *fileManeger = [NSFileManager defaultManager]; //文件夾路徑操作 NSString *homePath = NSHomeDirectory();homePath = [homePath stringByAppendingPathComponent:@'男神'];[fileManeger createDirectoryAtPath:homePath withIntermediateDirectories:YES attributes:nil error:nil ];homePath = [homePath stringByAppendingString:@'/god'];[fileManeger createFileAtPath:homePath contents:data attributes:nil]; /*UIImage *aImage = [UIImage imageWithContentsOfFile:homePath];UIImageView *aImageView = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];aImageView.image = aImage;[temp.view addSubview:aImageView]; */ //這里以刪除文件為例 BOOL res=[fileManeger removeItemAtPath:homePath error:nil]; if (res) { NSLog(@'文件刪除成功');}else NSLog(@'文件刪除失敗'); NSLog(@'文件是否存在: %@',[fileManeger isExecutableFileAtPath:homePath]?@'YES':@'NO'); }]; [downLoadTask resume];
文/劉高見(簡書作者) 原文鏈接:http://www.jianshu.com/p/e41e73f4edec
相關文章: