標籤:style blog color io os ar 使用 for strong
在iOS上的歸檔和在Mac上的歸檔有些不一樣, 在Mac上的歸檔你可以把檔案放在任意的一個檔案夾裡面, 但是在iOS上, 你所寫的檔案就只能放在三個檔案夾裡, 分別是Documents, Library, tmp三個檔案, 這裡需要注意一下, library和tmp檔案會在軟體升級, 系統升級或者系統空間不足時會自動清除裡面的檔案, 只有在Documents檔案才可以永久儲存, 直到你把軟體刪除為止.
這裡涉及的方法:
NSHomeDirectory:這個方法的意思就是擷取軟體的主目錄.
stringByAooendingPathComponent:這個方法的意思就是在目錄後添加一個檔案.
下面我們來看看例子:
#import "ViewController.h"#define PZ NSLog(@"----我是一條華麗的分割線----");@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; //擷取軟體的主目錄並且在Documents目錄下添加test.txt檔案. NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/test.txt"]; //建立檔案的路徑為path. [[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil]; NSString *str = @"Hello, world!"; //2.唯寫的方式開啟檔案, 並且把檔案的寫入路徑賦給了writeHanle. NSFileHandle *writeHanle = [NSFileHandle fileHandleForWritingAtPath:path]; //把str裡的字串以UTF8編碼存入data, 在這裡就完成了歸檔. NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding]; //解檔: 把歸檔好的二進位代碼以UTF8編碼格式轉換好賦給了字串對象str2. NSString *str2 = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", str2); //開啟檔案後要記得關閉, 就和記憶體管理一樣. [writeHandle closeFile];}- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}@end
輸出的結果:
2014-10-19 17:31:57.039 FileHandleDemo[12364:672084] Hello, world!
NSCoding的使用方法---iOS上的歸檔.