檔案載入和儲存

來源:互聯網
上載者:User

1、使用屬性列表儲存對象:
在Cocoa中,與一類名為屬性列表的對象,常簡稱為plist。這些列表包含Cocoa知道如何操作的一組對象。具體來講,Cocoa知道如何將它們儲存到檔案中並進行載入。屬性列表類包括:NSArray,NSDictionary,NSString和NSData,以及它們的變體(Mutable)

eg:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];NSArray *array = [NSArray arrayWithObjects:@"First",                              @"second",@"third",@"fourth",@"fifth",nil];[array writeToFile:@"array.plist" atomically:YES]; 

2、編碼對象
遺憾的是,無法總是將對象資訊表示為屬性列表類。如果能將所有對象都表示為數組字典,我們就沒有必要使用自己的類了。所幸,Cocoa具備一種機制來將對象自身轉化為某種格式並儲存到磁碟中。對象可以將它們的執行個體變數和其它資料編碼為資料區塊,然後儲存到磁碟中。遺憾將這些資料區塊讀到記憶體中,並且還能基於儲存的資料建立新對象。這個過程稱為編碼和解碼,或稱為序列化和還原序列化。
    通過NSCoding協議,可以使用自己的對象實現相同功能,實現它的兩個方法:
- (void)encodeWithCoder:(NSCoder *)aCoder;
- (id)initWithCoder:(NSCoder *)aDecoder;
NSCoder是一個抽象類別,定義一些有用的方法來在對象與NSData之間來迴轉換。完全不需要建立新NSCoder,因為它事件上並無多大作用。但是我們實際上要使用NSCoder的一些具體子類來編碼和解碼對象。我們將使用其中兩個子類NSKeyedArchiver和NSKeyedUnArchiver.
下面是一個例子:
標頭檔類BookObj.h的源碼:

////  BookObj.h//#import <Cocoa/Cocoa.h>@interface BookObj:NSObject<NSCoding>{    NSString *bookName;    NSString *author;}@property (copy) NSString *bookName;@property (copy) NSString *author;-(id)initWithName:(NSString *)name           author:(NSString *) au ;@end

實作類別BookObj.m的源碼:

////  BookObj.m//#import "BookObj.h"@implementation BookObj@synthesize bookName;@synthesize author;-(id)initWithName:(NSString *)name           author:(NSString *) au{    if (self = [super init]) {        self.bookName = name;        self.author = au;    }    return self;}- (void)encodeWithCoder:(NSCoder *)aCoder{    [aCoder encodeObject:self.bookName forKey:@"bookName"];    [aCoder encodeObject:self.author    forKey:@"author"];}- (id)initWithCoder:(NSCoder *)aDecoder{    if (self =[super init]) {        self.bookName = [aDecoder decodeObjectForKey:@"bookName"];        self.author = [aDecoder decodeObjectForKey:@"author"];    }    return self;}int main(int argc ,const char *argv[]){    BookObj *bookObj = [[BookObj alloc] initWithName:@"iPhone編程指南"                                              author:@"David"];        [NSKeyedArchiver archiveRootObject:bookObj toFile:@"bookObj.plist"];    NSLog(@"Success to archive file bookObj.plist!");    BookObj *bookOb =   [NSKeyedUnarchiver unarchiveObjectWithFile:@"bookObj.plist"];        NSLog(@"The book name is :%@",bookOb.author);    return 0;}@end

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.