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

Documents:用來存儲(chǔ)永久性的數(shù)據(jù)的文件 程序運(yùn)行時(shí)所需要的必要的文件都存儲(chǔ)在這里(數(shù)據(jù)庫)itunes會(huì)自動(dòng)備份這里面的文件Library:用于保存程序運(yùn)行期間生成的文件Caches:文件夾用于保存程序運(yùn)行期間產(chǎn)生的緩存文件Preferences:主要是保存一些用戶偏好設(shè)置的信息,一般情況下,我們不直接打開這個(gè)文件夾 而是通過NSUserDefaults進(jìn)行偏好設(shè)置的存儲(chǔ)tmp:臨時(shí)文件夾---程序運(yùn)行期間產(chǎn)生的臨時(shí)歲騙會(huì)保存在這個(gè)文件夾中 通常文件下載完之后或者程序退出的灰自動(dòng)清空此文件夾itunes不會(huì)備份這里的數(shù)據(jù)。 ~~~~tips: 由于系統(tǒng)會(huì)清空此文件夾所以下載或者其他臨時(shí)文件若需要持久化請(qǐng)及時(shí)移走
//第一個(gè)參數(shù):要查詢的文件的路徑 //第二個(gè)參數(shù):要查詢路徑所屬的用戶 iOS是單用戶 //第三個(gè)參數(shù)的意思 YES是絕對(duì)路徑 NO是相對(duì)路徑 //區(qū)別于OS-X系統(tǒng) iOS應(yīng)用文件夾中通常只有一個(gè)文件路徑 由于OC同時(shí)支持的蘋果系列產(chǎn)品的開發(fā) 在MacOS里面會(huì)同時(shí)存在很多軟件 通常生成的路徑放在一個(gè)數(shù)組里面 //iOS端一次只有一個(gè)應(yīng)用 所以取數(shù)組唯一的一個(gè)元素即可 NSArray *documentArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, NO); NSLog(@'%@',documentArray);//打印的結(jié)果是 '~/Documents' NSString *documentPath = [documentArray firstObject]; NSLog(@'documentPath = %@',documentPath);//結(jié)果是 ~/Documents 對(duì)比以上我們可以打印試著獲取幾個(gè)路徑 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);
另外 在這里值得我們注意的一點(diǎn)是:.app的路徑 iOS 8 之前bundle和tmp等文件統(tǒng)一放在主路徑下(home)---iOS 8 之后boundle放在了container文件夾的下面
二、簡單對(duì)象寫入文件1、NSString 寫入文件 讀取//準(zhǔn)備字符串 NSString *string = @'I love my iOS teacher'; //2 準(zhǔn)備路徑 NSString *path =NSHomeDirectory(); path = [path stringByAppendingString:@'/見哥.txt']; //3 寫入文件 // 3.1第一個(gè)參數(shù) 路徑 // 3.2第二個(gè)參數(shù) 是否進(jìn)行線性操作(YES保證發(fā)生意外時(shí)有中轉(zhuǎn)文件來保存信息 直至寫入完成 但是損耗大. NO的時(shí)候?qū)懭胨俣瓤?但是沒有安全保障) // 3.3第三個(gè)參數(shù) 編碼方式 // 3.4第四個(gè)參數(shù) 錯(cuò)誤對(duì)象 [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對(duì)象寫入 讀取
我們搞一張圖片 (波多老師喲~) 為例
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];三、復(fù)雜對(duì)象寫入文件
簡單對(duì)象可以通過writeTofile寫入對(duì)象 但是復(fù)雜對(duì)象沒有writeToFile的方法寫入文檔,所以我們需要借助歸檔和反歸檔,將復(fù)雜對(duì)象轉(zhuǎn)化成簡單對(duì)象,寫入文檔首先, 我們x-code新建一個(gè)類 SingleVip 繼承與NSObject 遵守 NSCoding協(xié)議
.h #import <Foundation/Foundation.h> @interface SingleVip : NSObject<NSCoding> @property(nonatomic,strong)NSString *name; @property(nonatomic,strong)NSString *assets;//資產(chǎn) @property(nonatomic,strong)NSString *car; @property(nonatomic,assign)int age; @end .m #import 'SingleVip.h' //定義成宏 方便下面使用 也可以減少出錯(cuò) #define kName @'name' #define kAssets @'assets' #define kCar @'car' #define kAge @'age' @implementation SingleVip #pragma mark---NSCoding必須實(shí)現(xiàn)的兩個(gè)----- //編碼 這個(gè)方法就是將對(duì)象轉(zhuǎn)化成data的時(shí)候會(huì)執(zhí)行的 - (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
在以上基礎(chǔ)上 我們創(chuàng)建一個(gè)SingleVip類的實(shí)例變量 進(jìn)行歸檔和反歸檔的操作 直接上代碼吧、、、往下看
SuperMan *man =[SuperMan new]; man.name = @'見哥'; man.age = 18; man.car = @'鳳凰牌大聯(lián)合'; man.assets = @'窮類屌蛋精光'; // //準(zhǔn)備路徑 NSString *homePath =NSHomeDirectory(); homePath = [homePath stringByAppendingString:@'/鉆石王老五.txt']; // //創(chuàng)建數(shù)據(jù)對(duì)象 用來存放vip對(duì)象 NSMutableData *data =[NSMutableData data]; // //創(chuàng)建歸檔對(duì)象 NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data]; // //開始?xì)w檔 [archiver encodeObject:vip forKey:@'vip']; // //完成歸檔 [archiver finishEncoding]; // //寫入文件 [data writeToFile:homePath atomically:YES]; //反歸檔 //將文件里面的data對(duì)象讀取出來 NSData *_data = [NSData dataWithContentsOfFile:homePath]; //創(chuàng)建反歸檔對(duì)象 NSKeyedUnarchiver *unArchiver =[[NSKeyedUnarchiver alloc]initForReadingWithData:_data]; SingleVip *_vip = [unArchiver decodeObjectForKey:@'vip']; [unArchiver finishDecoding];//完成反歸檔 NSLog(@'%@',_vip.name);
在這里有一點(diǎn)是需要我們區(qū)分的,歸檔并不是數(shù)據(jù)持久化的方式 而是輔助復(fù)雜對(duì)象轉(zhuǎn)化成簡單對(duì)象的一種方式 其實(shí)真正實(shí)現(xiàn)數(shù)據(jù)持久化的仍然是寫入文件writeToFile
iOS常見的數(shù)據(jù)持久化的方式 主要有以下幾點(diǎn):// plist (屬性列表)// NSUserDefaults 偏好設(shè)置 單例// writeToFile 寫入文件// SQLite 數(shù)據(jù)庫// 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對(duì)象 NSData *data = [NSData dataWithContentsOfURL:location]; //創(chuàng)建文件管理者對(duì)象 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
相關(guān)文章:
1. phpstudy apache開啟ssi使用詳解2. vue3+ts+elementPLus實(shí)現(xiàn)v-preview指令3. Xml簡介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理4. JSP之表單提交get和post的區(qū)別詳解及實(shí)例5. 詳解瀏覽器的緩存機(jī)制6. xml中的空格之完全解說7. jsp實(shí)現(xiàn)登錄驗(yàn)證的過濾器8. jsp文件下載功能實(shí)現(xiàn)代碼9. 使用Hangfire+.NET 6實(shí)現(xiàn)定時(shí)任務(wù)管理(推薦)10. 如何在jsp界面中插入圖片
