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

Documents:用來存儲永久性的數(shù)據(jù)的文件 程序運(yùn)行時所需要的必要的文件都存儲在這里(數(shù)據(jù)庫)itunes會自動備份這里面的文件Library:用于保存程序運(yùn)行期間生成的文件Caches:文件夾用于保存程序運(yùn)行期間產(chǎn)生的緩存文件Preferences:主要是保存一些用戶偏好設(shè)置的信息,一般情況下,我們不直接打開這個文件夾 而是通過NSUserDefaults進(jìn)行偏好設(shè)置的存儲tmp:臨時文件夾---程序運(yùn)行期間產(chǎn)生的臨時歲騙會保存在這個文件夾中 通常文件下載完之后或者程序退出的灰自動清空此文件夾itunes不會備份這里的數(shù)據(jù)。 ~~~~tips: 由于系統(tǒng)會清空此文件夾所以下載或者其他臨時文件若需要持久化請及時移走
//第一個參數(shù):要查詢的文件的路徑 //第二個參數(shù):要查詢路徑所屬的用戶 iOS是單用戶 //第三個參數(shù)的意思 YES是絕對路徑 NO是相對路徑 //區(qū)別于OS-X系統(tǒng) iOS應(yīng)用文件夾中通常只有一個文件路徑 由于OC同時支持的蘋果系列產(chǎn)品的開發(fā) 在MacOS里面會同時存在很多軟件 通常生成的路徑放在一個數(shù)組里面 //iOS端一次只有一個應(yīng)用 所以取數(shù)組唯一的一個元素即可 NSArray *documentArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, NO); NSLog(@'%@',documentArray);//打印的結(jié)果是 '~/Documents' NSString *documentPath = [documentArray firstObject]; NSLog(@'documentPath = %@',documentPath);//結(jié)果是 ~/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);
另外 在這里值得我們注意的一點(diǎn)是:.app的路徑 iOS 8 之前bundle和tmp等文件統(tǒng)一放在主路徑下(home)---iOS 8 之后boundle放在了container文件夾的下面
二、簡單對象寫入文件1、NSString 寫入文件 讀取//準(zhǔn)備字符串 NSString *string = @'I love my iOS teacher'; //2 準(zhǔn)備路徑 NSString *path =NSHomeDirectory(); path = [path stringByAppendingString:@'/見哥.txt']; //3 寫入文件 // 3.1第一個參數(shù) 路徑 // 3.2第二個參數(shù) 是否進(jìn)行線性操作(YES保證發(fā)生意外時有中轉(zhuǎn)文件來保存信息 直至寫入完成 但是損耗大. NO的時候?qū)懭胨俣瓤?但是沒有安全保障) // 3.3第三個參數(shù) 編碼方式 // 3.4第四個參數(shù) 錯誤對象 [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];三、復(fù)雜對象寫入文件
簡單對象可以通過writeTofile寫入對象 但是復(fù)雜對象沒有writeToFile的方法寫入文檔,所以我們需要借助歸檔和反歸檔,將復(fù)雜對象轉(zhuǎn)化成簡單對象,寫入文檔首先, 我們x-code新建一個類 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' //定義成宏 方便下面使用 也可以減少出錯 #define kName @'name' #define kAssets @'assets' #define kCar @'car' #define kAge @'age' @implementation SingleVip #pragma mark---NSCoding必須實現(xiàn)的兩個----- //編碼 這個方法就是將對象轉(zhuǎn)化成data的時候會執(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)建一個SingleVip類的實例變量 進(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ù)對象 用來存放vip對象 NSMutableData *data =[NSMutableData data]; // //創(chuàng)建歸檔對象 NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data]; // //開始?xì)w檔 [archiver encodeObject:vip forKey:@'vip']; // //完成歸檔 [archiver finishEncoding]; // //寫入文件 [data writeToFile:homePath atomically:YES]; //反歸檔 //將文件里面的data對象讀取出來 NSData *_data = [NSData dataWithContentsOfFile:homePath]; //創(chuàng)建反歸檔對象 NSKeyedUnarchiver *unArchiver =[[NSKeyedUnarchiver alloc]initForReadingWithData:_data]; SingleVip *_vip = [unArchiver decodeObjectForKey:@'vip']; [unArchiver finishDecoding];//完成反歸檔 NSLog(@'%@',_vip.name);
在這里有一點(diǎn)是需要我們區(qū)分的,歸檔并不是數(shù)據(jù)持久化的方式 而是輔助復(fù)雜對象轉(zhuǎn)化成簡單對象的一種方式 其實真正實現(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對象 NSData *data = [NSData dataWithContentsOfURL:location]; //創(chuàng)建文件管理者對象 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. React+umi+typeScript創(chuàng)建項目的過程2. ASP中常用的22個FSO文件操作函數(shù)整理3. ASP編碼必備的8條原則4. ASP調(diào)用WebService轉(zhuǎn)化成JSON數(shù)據(jù),附j(luò)son.min.asp5. 三個不常見的 HTML5 實用新特性簡介6. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報錯問題分析7. SharePoint Server 2019新特性介紹8. 無線標(biāo)記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁9. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過程解析10. php測試程序運(yùn)行速度和頁面執(zhí)行速度的代碼
