標籤:style blog color io os ar 使用 for strong
上一章我們介紹了在iOS上的歸檔以及解檔, 今天我們在歸檔之後稍微做一些改變, 使得解檔之後得到的結果有所不同, 這個方法類似NSMutableXXX, 可修改裡面的參數, 下面讓我們來看看吧.
涉及的方法:
seekToFileOffset:這個方法是尋求方法的位移, 意思就是在檔案中尋找文本裡的起點.
readDataOfLength:這個方法是指讀取檔案的長度是多少.
offsetInFile:是指寫到第幾個位置.
#import "ViewController.h"#define PZ NSLog(@"----我是一條華麗的分割線----");@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/test.txt"];// NSLog(@"%@", path); //1.建立檔案 [[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil]; NSString *str = @"Hello, world!"; PZ; //2.唯寫的方式開啟檔案, feleHandleForWritingAtPath是返回一個唯寫的方法. NSFileHandle *writeHanle = [NSFileHandle fileHandleForWritingAtPath:path]; //把str裡的字串以UTF8編碼存入data. NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding]; //把data裡的東西存入writeHandle [writeHanle writeData:data]; //再一次添加, 會直接加到前一個字串的後面. [writeHanle writeData:data]; PZ; //seekToFileOffset:0 是指跳到檔案開頭. [writeHanle seekToFileOffset:0]; //把字串@"xxx"以UTF8編碼寫入writeHanle檔案中. [writeHanle writeData:[@"xxx" dataUsingEncoding:NSUTF8StringEncoding]]; //offsetInFile是指寫到第幾個位置. NSLog(@"%llu", writeHanle.offsetInFile); PZ; //4.關閉檔案 [writeHanle closeFile]; PZ; //使用fileURLWithpath讀取path的路徑. NSURL *url = [NSURL fileURLWithPath:path]; //再把url裡面的傳給readHandle. NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingFromURL:url error:nil]; //offsetInFile是指寫到第幾個位置. NSLog(@"%llu -----", readHandle.offsetInFile); //seekToFileOffset:是指定檔案的位移量. [readHandle seekToFileOffset:0]; //readDataOfLength:的意思就是閱讀readHandle文檔中10的長度內容. NSData *data1 = [readHandle readDataOfLength:10]; //把二進位檔案data1以UTF8編碼存入NSString對象str2中. NSString *str2 = [[NSString alloc]initWithData:data1 encoding:NSUTF8StringEncoding]; //關閉檔案 NSLog(@"%@", str2); [readHandle closeFile];}- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}@end
輸出的結果:
2014-10-19 19:41:58.407 FileHandleDemo[13118:714260] 32014-10-19 19:41:58.407 FileHandleDemo[13118:714260] 0 -----2014-10-19 19:41:58.407 FileHandleDemo[13118:714260] xxxlo, wor
NSCoding的使用方法---iOS上的歸檔(增加更改內容的方法).