標籤:
在日常開發中對於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