下面介绍下Object C中通过NSKeyedArchiver序列化与反序列化:
序列化中将对象写到文件中,反序列化则从文件中读取数据并构造对象。NSKeyedArchiver需要实现NSCoding中的两个函数initWithcoder()和encodeWithCoder()。
代码如下 :
// // SoreCard.h // SerializationTest // 序列化与反序列化 // Created by Dwen on 12-11-22. // Copyright (c) 2012年 __MyCompanyName__. All rights reserved. // #import <Foundation/Foundation.h> @interface SoreCard : NSObject<NSCoding> @property (strong,nonatomic) NSString *bestTime; @property (strong,nonatomic) NSMutableArray *allTime; - (void) create; - (void) print; @end
#import "SoreCard.h" @implementation SoreCard @synthesize bestTime; @synthesize allTime; - (id)initWithCoder:(NSCoder *)aDecoder{ if (self == [super init]) { bestTime = [aDecoder decodeObjectForKey:@"bestTime"]; allTime = [aDecoder decodeObjectForKey:@"allTime"]; } return self; } - (void)encodeWithCoder:(NSCoder *)aCoder{ [aCoder encodeObject:bestTime forKey:@"bestTime"]; [aCoder encodeObject:allTime forKey:@"allTime"]; } - (void) create{ bestTime = @"序列化与反序列化测试"; allTime = [[NSMutableArray alloc] initWithObjects:@"中国",@"美国",@"德国", nil]; } - (void) print{ NSLog(@"BestTime name : %@",bestTime); for(NSString *str in allTime){ NSLog(@"str : %@",str); } } @end
// // main.m // SerializationTest // // Created by on 12-11-22. // Copyright (c) 2012年 __MyCompanyName__. All rights reserved. // #import <UIKit/UIKit.h> #import "AppDelegate.h" #import "SoreCard.h" #define ARCHIVE 0 #define UNARCHIVE 1 int main(int argc, char *argv[]) { @autoreleasepool { //路径 NSString *homePath = [[NSBundle mainBundle] executablePath]; NSArray *strings = [homePath componentsSeparatedByString: @"/"]; NSString *executableName = [strings objectAtIndex:[strings count]-1]; NSString *baseDirectory = [homePath substringToIndex: [homePath length]-[executableName length]-1]; // NSString *fileName = [NSString stringWithFormat:@"%@/roster.archive",baseDirectory]; NSString *fileName = [NSString stringWithFormat:@"%@/test.txt",baseDirectory]; NSLog(@"filePath: %@",fileName); #if ARCHIVE SoreCard *card = [[SoreCard alloc] init]; [card create]; //将类写入文件 [NSKeyedArchiver archiveRootObject:card toFile:fileName]; #endif #if UNARCHIVE //将类从文件中读出 SoreCard *soreCard = [NSKeyedUnarchiver unarchiveObjectWithFile:fileName]; [soreCard print]; #endif return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } }