中文字幕在线观看,亚洲а∨天堂久久精品9966,亚洲成a人片在线观看你懂的,亚洲av成人片无码网站,亚洲国产精品无码久久久五月天

淺談iOS的文件操作

2018-07-20    來源:編程學習網(wǎng)

容器云強勢上線!快速搭建集群,上萬Linux鏡像隨意使用


一、沙盒路徑

沙盒主路徑:是程序運行期間系統(tǒng)會生成一個專屬的沙盒路徑,應用程序在使用期間非代碼的文件都存儲在當前的文件夾路徑里面
我們通過以下代碼可以打印出沙盒主路徑

NSString *homePath =NSHomeDirectory(); NSLog(@"%@",homePath);

我們根據(jù)打印出的路徑前往文件夾可以進入包含 Documents Library 和 tmp文件夾的文件夾 這個就是沙盒主路徑



Documents:用來存儲永久性的數(shù)據(jù)的文件 程序運行時所需要的必要的文件都存儲在這里(數(shù)據(jù)庫)itunes會自動備份這里面的文件
Library:用于保存程序運行期間生成的文件
Caches:文件夾用于保存程序運行期間產(chǎn)生的緩存文件
Preferences:主要是保存一些用戶偏好設置的信息,一般情況下,我們不直接打開這個文件夾 而是通過NSUserDefaults進行偏好設置的存儲
tmp:臨時文件夾---程序運行期間產(chǎn)生的臨時歲騙會保存在這個文件夾中 通常文件下載完之后或者程序退出的灰自動清空此文件夾itunes不會備份這里的數(shù)據(jù)。 ~~~~tips: 由于系統(tǒng)會清空此文件夾所以下載或者其他臨時文件若需要持久化請及時移走

//第一個參數(shù):要查詢的文件的路徑 //第二個參數(shù):要查詢路徑所屬的用戶 iOS是單用戶 //第三個參數(shù)的意思 YES是絕對路徑 NO是相對路徑 //區(qū)別于OS-X系統(tǒng) iOS應用文件夾中通常只有一個文件路徑 由于OC同時支持的蘋果系列產(chǎn)品的開發(fā) 在MacOS里面會同時存在很多軟件 通常生成的路徑放在一個數(shù)組里面 //iOS端一次只有一個應用 所以取數(shù)組唯一的一個元素即可 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等文件統(tǒng)一放在主路徑下(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第一個參數(shù) 路徑 //    3.2第二個參數(shù) 是否進行線性操作(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];

三、復雜對象寫入文件

簡單對象可以通過writeTofile寫入對象 但是復雜對象沒有writeToFile的方法寫入文檔,所以我們需要借助歸檔和反歸檔,將復雜對象轉(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

在以上基礎上 我們創(chuàng)建一個SingleVip類的實例變量 進行歸檔和反歸檔的操作 直接上代碼吧、、、往下看

SuperMan *man =[SuperMan new];
    man.name = @"見哥";
    man.age = 18;
    man.car = @"鳳凰牌大聯(lián)合";
    man.assets = @"窮類屌蛋精光"; //    //準備路徑 NSString *homePath =NSHomeDirectory();
    homePath = [homePath stringByAppendingString:@"/鉆石王老五.txt"]; //    //創(chuàng)建數(shù)據(jù)對象 用來存放vip對象 NSMutableData *data =[NSMutableData data]; //    //創(chuàng)建歸檔對象 NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data]; //    //開始歸檔 [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);

在這里有一點是需要我們區(qū)分的,歸檔并不是數(shù)據(jù)持久化的方式 而是輔助復雜對象轉(zhuǎn)化成簡單對象的一種方式 其實真正實現(xiàn)數(shù)據(jù)持久化的仍然是寫入文件writeToFile

iOS常見的數(shù)據(jù)持久化的方式 主要有以下幾點:
// plist (屬性列表)
// NSUserDefaults 偏好設置 單例
// 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 

標簽: 安全 代碼 數(shù)據(jù)庫 寫入速度

版權申明:本站文章部分自網(wǎng)絡,如有侵權,請聯(lián)系:west999com@outlook.com
特別注意:本站所有轉(zhuǎn)載文章言論不代表本站觀點!
本站所提供的圖片等素材,版權歸原作者所有,如需使用,請與原作者聯(lián)系。

上一篇:Scala學習資源整理

下一篇:編碼過程中,需要注意的地方