天天看點

擷取沙盒路徑

// 擷取沙盒路徑

// 參數1. 設定擷取哪個檔案路徑 擷取NSDocumentDirectory路徑

// 參數2. 設定從哪個路徑下搜尋 從user路徑開始搜尋

// 參數3, 設定絕對路徑或者相對路徑 yes是絕對

NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

// Documents 用來存放使用者資料, 比如備份檔案, 存儲資訊

// Library 下面有兩個檔案夾

// 第一個是caches檔案夾, 用來存系統的緩存檔案資料

// 第二個是Preferences檔案夾, 用來存系統的配置檔案, 比如系統的偏好設定檔案等

// tem 檔案夾是用來存系統的臨時檔案, 當程式退出後這裡的檔案将會被清空

// 擷取document路徑
NSString *DocumentsPath = [array lastObject];
// 拼接檔案路徑 隻是拼接了一個.txt檔案的路徑, 但并沒有建立
NSString *studentFilePath = [DocumentsPath stringByAppendingPathComponent:@"student.txt"];
// 要想生成.txt檔案, 必須要往該檔案裡面寫入資料
NSString *name = @"德瑪西亞";
// 将字元串寫入到檔案中
// 參數1. 寫入檔案的路徑
// 參數2. 是否受到保護
// 參數3. 編碼格式
// 參數4. 錯誤資訊
BOOL result = [name writeToFile:studentFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
if (result) {
    NSLog(@"寫入成功");
} else {
    NSLog(@"寫入失敗");
}

// 往student.xml檔案中寫入數組
// 建立數組
NSArray *array2 = [NSArray arrayWithObjects:@"哦三",@"西北雨",@"大水别", nil];
// 拼接檔案路徑
NSString *studentXml = [DocumentsPath stringByAppendingPathComponent:@"student.xml"];
// 将數組寫入到檔案
BOOL result2 = [array2 writeToFile:studentXml atomically:YES];
if (result2) {
    NSLog(@"寫入成功");
} else {
    NSLog(@"寫入失敗");
}


// 将字典寫入到plist檔案中
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"李四", @"name", @"33", @"age", @"男", @"gender", nil];
NSString *dicFilePath = [DocumentsPath stringByAppendingPathComponent:@"student.plist"];
BOOL result3 = [dic writeToFile:dicFilePath atomically:YES];
if (result3) {
    NSLog(@"寫入成功");
} else {
    NSLog(@"寫入失敗");
}

// 特殊類型的資料, 比如model, 學生類, 就不能直接寫入了 需要使用歸檔: 所謂歸檔就是将類似model這樣特殊的資料存入本地檔案中
#warning 歸檔第一步 建立一個學生類(student.h和student.m)
#warning 歸檔第二步 簽訂NSCoding協定(student.h中簽訂)
#warning 歸檔第三步 對model進行編碼(student.m)
/*
 -(void)encodeWithCoder:(NSCoder *)aCoder
 {
 // 參數1. 目前model的屬性對象, key就是屬性名
 [aCoder encodeObject:self.name forKey:@"name"];
 [aCoder encodeObject:self.gender forKey:@"gender"];
 // Integer用Integer類型
 [aCoder encodeInteger:self.age forKey:@"age"];
 }
 */
#warning 歸檔第四步 解碼(student.m)
/*
 -(id)initWithCoder:(NSCoder *)aDecoder
 {
 self = [super init];
 if (self) {
 // 解碼取值, 并指派給model屬性
 self.name = [aDecoder decodeObjectForKey:@"name"];
 self.gender = [aDecoder decodeObjectForKey:@"gender"];
 self.age = [aDecoder decodeIntegerForKey:@"age"];
 }
 return self;
 }
 */
#warning 歸檔第五步 對model進行歸檔操作(Viewdidload)
/*
 Student *stu = [[Student alloc] init];
 stu.name = @"囖類";
 stu.gender = @"d";
 stu.age = 20;
 // 拼接檔案路徑
 NSString *modelFilePath = [DocumentsPath stringByAppendingPathComponent:@"student.lol"];
 // 進行歸檔(類似寫入檔案) 使用歸檔類NSKeyedArchiver進行歸檔操作
 BOOL result4 = [NSKeyedArchiver archiveRootObject:stu toFile:modelFilePath];
 if (result4) {
 NSLog(@"寫入成功");
 } else {
 NSLog(@"寫入失敗");
 }
 // 反歸檔
 Student *myStu = [NSKeyedUnarchiver unarchiveObjectWithFile:modelFilePath];
 NSLog(@"name  = %@  gender = %@  age = %ld", myStu.name, myStu.gender, myStu.age);
 */
           

繼續閱讀