objective-c基于key的序列化和反序列化

来源:互联网 发布:java http请求 编辑:程序博客网 时间:2024/05/29 03:13

序列化和反序列化自己定义的类,注意以下代码不保证引用计数的正确性,还没有学到这些。

#import <Foundation/Foundation.h>@interface ClassA: NSObject <NSCoding>{NSString *name;int size;float money;NSArray *array;}@property (retain) NSString *name;@property int size;@property float money;@property (copy) NSArray *array;@end@implementation ClassA@synthesize name;@synthesize size;@synthesize money;@synthesize array;-(id) init{if (self = [super init]){name = [NSString stringWithFormat: @"%@=100", @"hello"];size = 99;money = 88.7654321;array = [NSArray arrayWithObjects: @"world", [NSNumber numberWithInt: 10], [NSNull null], nil];}return self;}-(NSString *) description{NSString *desc = [NSString stringWithFormat: @"name=%@ size=%i money=%f array=%@", name, size, money, array];return desc;}-(void) encodeWithCoder: (NSCoder *) aCoder{[aCoder encodeObject: self.name forKey: @"name"];[aCoder encodeInt: self.size forKey: @"size"];[aCoder encodeFloat: self.money forKey: @"money"];[aCoder encodeObject: self.array forKey: @"array"];}-(id) initWithCoder: (NSCoder *) aDecoder{if (self = [super init]){self.name = [aDecoder decodeObjectForKey: @"name"];self.size = [aDecoder decodeIntForKey: @"size"];self.money = [aDecoder decodeFloatForKey: @"money"];self.array = [aDecoder decodeObjectForKey: @"array"];}return self;}@endint main(const int argc, const char *argv[]){NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];    ClassA *ca = [ClassA new];    NSLog(@"1 %@", ca);    [NSKeyedArchiver archiveRootObject: ca toFile: @"ca.bin"];    [ca release];    ClassA *ca1 = [NSKeyedUnarchiver unarchiveObjectWithFile: @"ca.bin"];    NSLog(@"2 %@", ca1);[pool drain];return 0;}

windows下输出结果
C:\GNUstep\msys\1.0\home\pro\cpro>cpro.exe
2015-02-05 10:10:33.989 cpro[5852] 1 name=hello=100 size=99 money=88.765434 array=(world, 10, "<null>")
2015-02-05 10:10:34.033 cpro[5852] 2 name=hello=100 size=99 money=88.765434 array=(world, 10, "<null>")
序列化以后生成的二进制文件。






0 0