NSCoding的使用方法---iOS上的歸檔.

來源:互聯網
上載者:User

標籤:style   blog   color   io   os   ar   使用   for   strong   

在iOS上的歸檔和在Mac上的歸檔有些不一樣, 在Mac上的歸檔你可以把檔案放在任意的一個檔案夾裡面, 但是在iOS上, 你所寫的檔案就只能放在三個檔案夾裡, 分別是Documents, Library, tmp三個檔案, 這裡需要注意一下, librarytmp檔案會在軟體升級, 系統升級或者系統空間不足時會自動清除裡面的檔案, 只有在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上的歸檔.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.