[Objective-C] 011_資料持久化_NSKeyedArchiver

來源:互聯網
上載者:User

標籤:

在日常開發中對於NSString、NSDictionary、NSArray、NSData、NSNumber這些基本類的資料持久化,可以用屬性列表的方法持久化到.plist 檔案中。但是一些我們自訂的類的話,屬性列表的方法就不能用了,這時候是NSKeyedArchiver出馬的時候了。以我們前面寫的Person 類為例,看NSKeyedArchiver 如何一展身手。

Person 類

//////////////////     .h     ////////////////#import <Foundation/Foundation.h>@interface Person : NSObject<NSCoding>@property (nonatomic,copy)NSString *name;@property (nonatomic,assign)int age;@property (nonatomic,copy)NSString *sex;- (void)printInfo;@end//////////////////     .m    ////////////////#import "Person.h"@implementation Person@synthesize name = _name,sex = _sex;@synthesize age = _age;//寫入檔案-(void)encodeWithCoder:(NSCoder *)encoder{    [encoder encodeInt:self.age forKey:@"age"];    [encoder encodeObject:self.name forKey:@"name"];    [encoder encodeObject:self.sex forKey:@"sex"];}//從檔案中讀取-(id)initWithCoder:(NSCoder *)decoder{    self.age = [decoder decodeIntForKey:@"age"];    self.name = [decoder decodeObjectForKey:@"name"];    self.sex = [decoder decodeObjectForKey:@"sex"];    return self;}- (void)printInfo {    NSLog(@"我的名字叫:%@ 今年%d歲 我是一名%@ %@",self.name,self.age,self.sex,NSStringFromClass([self class]));}@end

AppDelegate.m 中測試

#import "AppDelegate.h"#import "Person.h"@interface AppDelegate ()@end@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    Person *person = [[[Person alloc] init] autorelease];    person.age = 18;    person.sex = @"男";    person.name = @"SuperDo.Horse";        //獲得Document的路徑    NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];    NSString *path = [documents stringByAppendingPathComponent:@"person.archiver"];//拓展名可以自訂    [NSKeyedArchiver archiveRootObject:person toFile:path];        Person *person2 = [NSKeyedUnarchiver unarchiveObjectWithFile:path];    [person2 printInfo];        return YES;}@end

列印結果:  

2015-07-05 22:37:48.876 Attendance[80142:2069100] 我的名字叫:SuperDo.Horse 今年18我是一名男 Person

 

  

 

 

本站文章為 寶寶巴士 SD.Team 原創,轉載務必在明顯處註明:(作者官方網站: 寶寶巴士 ) 
轉載自【寶寶巴士SuperDo團隊】 原文連結: http://www.cnblogs.com/superdo/p/4623177.html

 

 

[Objective-C] 011_資料持久化_NSKeyedArchiver

相關文章

聯繫我們

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