iOS ---沙盒

沙盒

沙盒:每個(gè)iOS應(yīng)用程序都會(huì)為自己創(chuàng)建一個(gè)文件系統(tǒng)目錄(文件夾), 這個(gè)獨(dú)立、封閉、安全的空間,叫做沙盒。
注:1.每個(gè)應(yīng)用程序都會(huì)有一個(gè)應(yīng)用程序沙盒
2.應(yīng)用程序沙盒就是文件系統(tǒng)目錄
沙盒機(jī)制:一種安全體系(安全機(jī)制)
沙盒機(jī)制特點(diǎn):1.每個(gè)應(yīng)用程序的活動(dòng)范圍都限定在自己的沙盒里
2.不能隨意跨越自己的沙盒去訪問(wèn)別的應(yīng)用程序沙盒中的內(nèi)容(iOS8已經(jīng)部分開放訪問(wèn))
3.應(yīng)用程序向外請(qǐng)求或接受數(shù)據(jù)都需要經(jīng)過(guò)權(quán)限認(rèn)證

沙盒目錄下有三個(gè)文件夾Documents Library(下面有Caches和Preference目錄) tmp

Documents目錄

保存應(yīng)用程序運(yùn)行時(shí)生成的需要持久化的數(shù)據(jù),Itunes會(huì)自動(dòng)備份該目錄

Library目錄

存儲(chǔ)程序的默認(rèn)設(shè)置和其他狀態(tài)信息,Itunes會(huì)自動(dòng)備份該目錄
1.Library/Caches:存放緩存文件,ITunes不會(huì)備份此目錄,此目錄下文件不會(huì)再應(yīng)用程序退出刪除。一般存放體積比較大,不是特別重要的資源。
2.Library/Preference:保存應(yīng)用的所有偏好設(shè)置,iOS的Setting(設(shè)置)應(yīng)用會(huì)在該目錄中查找應(yīng)用的設(shè)置信息,iTunes會(huì)自動(dòng)備份該目錄。注意:不應(yīng)該直接創(chuàng)建偏好設(shè)置文件,而是應(yīng)該使用NSUserDefaults類來(lái)取得和設(shè)置應(yīng)用程序的偏好。

tmp目錄

保存應(yīng)用運(yùn)行時(shí)所需要的臨時(shí)數(shù)據(jù),使用完畢后在將相應(yīng)的文件從該目錄刪除。應(yīng)用沒有運(yùn)行時(shí),系統(tǒng)也有可能會(huì)清除該目錄下的文件,iTunes不會(huì)同步該目錄。iPhone重啟時(shí),該目錄下的文件被刪除。

獲取沙盒路徑

NSString *path = NSHomeDirectory();

獲取沙盒下文件目錄的路徑
有三種獲取方法:
1.拼接字符串:

NSString *Documents = [path stringByAppendingString:@"/Documents"];

2.拼接路徑

NSString *Documents2 = [path stringByAppendingPathComponent:@"Documents"];

3.系統(tǒng)提供的獲取沙盒下目錄路徑的方法

NSString *Documents3 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, NO) firstObject];
//NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, NO) 方法返回值為只有一個(gè)元素的數(shù)組,所以去第一個(gè)元素

對(duì)于其他兩個(gè)文件路徑的獲取方式都一樣,系統(tǒng)提供的方法有些區(qū)別

NSString *library3 = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
//對(duì)于Library文件獲取路徑方法,只是參數(shù)有些不一樣
//獲取library下的caches
    NSString *cachesStr = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];

獲取tmp文件夾路徑(系統(tǒng)提供的方法)

NSString *tmpStr = NSTemporaryDirectory();

獲取程序包路徑

    NSString *appPath = [NSBundle mainBundle].resourcePath;

獲取程序包內(nèi)種的一個(gè)圖片資源(apple.png)路徑

    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"apple" ofType:@"png"];

簡(jiǎn)單對(duì)象的讀寫(I/O)操作

簡(jiǎn)單對(duì)象:字符串,數(shù)組,字典,data

字符串存儲(chǔ)

//獲取存儲(chǔ)的目錄
    NSString *str = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    //在沙盒文件夾下的Documents內(nèi)創(chuàng)建.txt文件
    NSString *newPath = [str stringByAppendingPathComponent:@"text.txt"];
    //存入內(nèi)容
    NSString *name = @"藍(lán)歐科技, nihao";
    
    [name writeToFile:newPath atomically:YES encoding:NSUTF8StringEncoding error:nil];

字符串讀取

NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *newPath = [path stringByAppendingString:@"/text.txt"];
NSString *string = [NSString stringWithContentsOfFile:newPath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@", string);

數(shù)組存儲(chǔ)

//獲取路徑
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    //創(chuàng)建文件
    NSString *newPath = [path stringByAppendingPathComponent:@"array.plist"];
    //存入的數(shù)組
    NSArray *nameArr = @[@"zhangsan", @"lisi", @"wangwu"];
    [nameArr writeToFile:newPath atomically:YES];

數(shù)組讀取

 NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *newPath = [path stringByAppendingString:@"/array.plist"];
    //獲取數(shù)組
    NSArray *array = [NSArray arrayWithContentsOfFile:newPath];
    NSLog(@"%@", array);

字典存儲(chǔ)

//獲取路徑
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    //新建plist文件
    NSString *newPath = [path stringByAppendingPathComponent:@"dict.plist"];
    //要存儲(chǔ)的字典
    NSArray *nameArr = @[@"zhangsan",@"lisi"];
    NSDictionary *dict = @{@"a" : @"1", @"b":@"2", @"c" : @"3" , @"name" : nameArr};
//    [dict setValue:nameArr forKey:@"name"];
    [dict writeToFile:newPath atomically:YES];

字典讀取

//獲取路徑
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    //獲取plist路徑
    NSString *newPath = [path stringByAppendingString:@"/dict.plist"];
    //獲取字典
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:newPath];
    NSLog(@"%@", dict);

NSData類型存儲(chǔ)

    NSString *str = @"nihoa";
    //獲取地址
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *dataPath = [path stringByAppendingPathComponent:@"data.plist"];
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    //寫入文件
    [data writeToFile:dataPath atomically:YES];

NSData讀取

  //獲取路徑
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *dataPath = [path stringByAppendingPathComponent:@"data.plist"];
    NSData *data = [NSData dataWithContentsOfFile:dataPath];
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@", str);

圖片存儲(chǔ)

//將圖片轉(zhuǎn)成NSData類型在存儲(chǔ)
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    //在沙盒問(wèn)價(jià)下面創(chuàng)建一個(gè)文件
    NSString *newPath = [path stringByAppendingPathComponent:@"image.png"];
    //需要存儲(chǔ)的圖片
    NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"tu.jpg"], 1.0);
    //創(chuàng)建文件并存儲(chǔ)
    [imageData writeToFile:newPath atomically:YES];

圖片讀取

//獲取沙盒地址
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    //獲取圖片data地址
    NSString *newPath = [path stringByAppendingPathComponent:@"image.png"];
    //獲取data
    NSData *data = [NSData dataWithContentsOfFile:newPath];
    //獲取圖片
    UIImage *image = [UIImage imageWithData:data];
    //添加imageView
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 200, 150, 150)];
    imageView.image = image;
    [self.view addSubview:imageView];

總結(jié)起來(lái)就是:簡(jiǎn)單對(duì)象的寫就是把在沙盒目錄下新建一個(gè)文件,將簡(jiǎn)單對(duì)象寫入進(jìn)文件就行,讀就是找到目標(biāo)文件,根據(jù)路徑創(chuàng)建對(duì)象就好

通過(guò)文件管理器來(lái)操作對(duì)象

創(chuàng)建對(duì)象

NSString *string = @"hello nihao";
    //根據(jù)字符串創(chuàng)建data
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];

創(chuàng)建文件管理器

    NSFileManager *fileManager = [[NSFileManager alloc] init];

存儲(chǔ)對(duì)象

//向目標(biāo)文件寫入信息
    BOOL save = [fileManager createFileAtPath:[[self documentPath] stringByAppendingPathComponent:@"studenttt.plist"] contents:data attributes:nil];
    if (save) {
        NSLog(@"寫入成功");
    }else{
        NSLog(@"寫入錯(cuò)誤");
    }
//注:[self documentPath]是獲取Documents路徑
//獲取Documents路徑
- (NSString *)documentPath {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
}

讀取對(duì)象

NSData *mData = [fileManager contentsAtPath:[[self documentPath] stringByAppendingPathComponent:@"studenttt.plist"]];
NSString *mStr = [[NSString alloc] initWithData:mData encoding:NSUTF8StringEncoding];

移動(dòng)文件

    //移動(dòng)文件
//atPath:文件存在當(dāng)前目錄
//toPath:目標(biāo)目錄
    BOOL result = [fileManager moveItemAtPath:[[self documentPath] stringByAppendingPathComponent:@"studenttt.plist"] toPath:[[self libraryPath] stringByAppendingPathComponent:@"studenttt.plist"] error:nil];
    if (result) {
        NSLog(@"移動(dòng)成功");
    }else{
        NSLog(@"移動(dòng)錯(cuò)誤");
    }
//注:[self libraryPath] 獲取library文件目錄
//獲取library路徑
- (NSString *)libraryPath {
    return [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
}

復(fù)制文件

  BOOL result = [fileManager copyItemAtPath:[[self documentPath] stringByAppendingPathComponent:@"studenttt.plist"] toPath:[[self libraryPath] stringByAppendingPathComponent:@"studenttt.plist"] error:nil];
    if (result) {
        NSLog(@"復(fù)制成功");
    }else{
        NSLog(@"復(fù)制錯(cuò)誤");
    }

比較不同路徑下的文件內(nèi)容是否相同

  BOOL result1 = [fileManager contentsEqualAtPath:[[self documentPath] stringByAppendingPathComponent:@"studenttt.plist"] andPath:[[self libraryPath] stringByAppendingPathComponent:@"studenttt.plist"]];
    if (result1) {
        NSLog(@"一致");
    }else{
        NSLog(@"不同");
    }

文件是否存在

  BOOL result = [fileManager fileExistsAtPath:[[self libraryPath] stringByAppendingPathComponent:@"studenttt.plist"]];
    if (result) {
        NSLog(@"存在");
    }else{
        NSLog(@"不存在");
    }

移除文件

    BOOL result = [fileManager removeItemAtPath:[[self libraryPath] stringByAppendingPathComponent:@"studenttt.plist"] error:nil];
    if(result){
        NSLog(@"移除成功");
    }else{
        NSLog(@"移除錯(cuò)誤");
    }

創(chuàng)建文件夾

    BOOL result = [fileManager createDirectoryAtPath:[[self documentPath] stringByAppendingPathComponent:@"nimeide"] withIntermediateDirectories:YES attributes:nil error:nil];
    if (result) {
        NSLog(@"創(chuàng)建成功");
    }else{
        NSLog(@"創(chuàng)建錯(cuò)誤");
    }

復(fù)雜對(duì)象的讀寫---歸檔和反歸檔

復(fù)雜對(duì)象:在Foundation框架內(nèi)不存在的數(shù)據(jù)類,如:自定義Person類無(wú)法再程序內(nèi)通過(guò)writeToFile:這個(gè)方法寫入到文件內(nèi)

如何將復(fù)雜對(duì)象寫入文件?

復(fù)雜對(duì)象無(wú)法通過(guò)writeFile:方法進(jìn)行數(shù)據(jù)持久化,只能通過(guò)將復(fù)雜對(duì)象轉(zhuǎn)化為NSData(這個(gè)步驟就是歸檔),然后再通過(guò)writeTiFile:寫入文件

如何從文件中讀取復(fù)雜對(duì)象?

從文件中讀取NSData數(shù)據(jù),將NSdata轉(zhuǎn)化為復(fù)雜對(duì)象(這個(gè)步驟就是反歸檔)
注:
1.復(fù)雜對(duì)象寫入文件的過(guò)程(復(fù)雜對(duì)象->歸檔->NSData->writeToFile:)
2.從文件中讀取出復(fù)雜對(duì)象過(guò)程(讀取文件->NSData->反歸檔->復(fù)雜對(duì)象)

如何進(jìn)行歸檔和反歸檔

1.首先,復(fù)雜對(duì)象所屬的類要遵循<NSCoding>協(xié)議

//Person.h
@interface Person : NSObject <NSCoding>
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *gender;
@property (nonatomic, assign) NSInteger age;
@end

2.其次,實(shí)現(xiàn)協(xié)議中的兩個(gè)方法

  • -(void)encodeWithCoder:(NSCoder *)aCoder;
  • -(instancetype)initWithCoder:(NSCoder *)aDecoder
//Person.m
@implementation Person
//當(dāng)對(duì)象進(jìn)行歸檔操作的時(shí)候,會(huì)自動(dòng)調(diào)用這個(gè)方法
- (void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeObject:self.gender forKey:@"gender"];
    [aCoder encodeInteger:self.age forKey:@"age"];
}
//當(dāng)對(duì)象進(jìn)行反歸檔的時(shí)候會(huì)調(diào)用
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super init]) {
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.age = [aDecoder decodeIntegerForKey:@"age"];
        self.gender = [aDecoder decodeObjectForKey:@"gender"];
    }
    return self;
}
@end

歸檔 ----NSKeyedArchiver

  Person *person = [[Person alloc] init];
    person.name = @"小明";
    person.age = 23;
    person.gender = @"男";
    
    //進(jìn)行歸檔操作
    //1.創(chuàng)建一個(gè)NSmutableData,用來(lái)存儲(chǔ)歸檔后的數(shù)據(jù)
    NSMutableData *mData = [[NSMutableData alloc] init];
    //2.創(chuàng)建歸檔器
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:mData];
    //進(jìn)行歸檔
    [archiver encodeObject:person forKey:@"person"];
    //歸檔結(jié)束
    [archiver finishEncoding];
    //存到沙盒的文件夾中
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *newPath = [path stringByAppendingPathComponent:@"guidang.plist"];
    //存儲(chǔ)data
    [mData writeToFile:newPath atomically:YES];

反歸檔 ----NSKeyedUnarchiver

   //獲取路徑
    NSString * newPath = [[self documentPath] stringByAppendingPathComponent:@"guidang.plist"];
    //取出數(shù)據(jù)
    NSData *data = [NSData dataWithContentsOfFile:newPath];
    //創(chuàng)建反歸檔器
    NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    Person *person = [unArchiver decodeObjectForKey:@"person"];
    //反歸檔結(jié)束
    [unArchiver finishDecoding];
    NSLog(@"name : %@ age : %ld gender : %@", person.name, person.age, person.gender);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • *面試心聲:其實(shí)這些題本人都沒怎么背,但是在上海 兩周半 面了大約10家 收到差不多3個(gè)offer,總結(jié)起來(lái)就是把...
    Dove_iOS閱讀 27,666評(píng)論 30 472
  • 1、簡(jiǎn)介 iOS系統(tǒng)相對(duì)于Android系統(tǒng)或者相對(duì)于Windows系統(tǒng)來(lái)說(shuō)比較安全的原因很多,其中有一點(diǎn)就是蘋果...
    三歲就很乖閱讀 1,394評(píng)論 0 1
  • 西風(fēng)綿綿掃落花,樹底秋千映殘霞。 群童嬉鬧總不倦,娘不喚崽不還家。
    霙愔閱讀 241評(píng)論 7 6
  • 上一篇簡(jiǎn)書是2月26日,小可愛出生的日子 一晃,小可愛101天了 “女大十八變”的魔法早早就起了作用,如今的小可愛...
    小小丹大世界閱讀 713評(píng)論 4 4
  • 我可以一個(gè)人上課,一個(gè)人吃飯,一個(gè)人走很遠(yuǎn)得路,一個(gè)人在人群里轉(zhuǎn)悠,一個(gè)人笑,一個(gè)人發(fā)呆,走很遠(yuǎn)的路只為滿足那個(gè)突...
    剽悍小美女閱讀 188評(píng)論 0 0

友情鏈接更多精彩內(nèi)容