//
//  codeObj.h
//  encodeObject
//
//  Created by 110 on 10-2-6.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//
 
#import <Cocoa/Cocoa.h>
 
@interface codeObj : NSObject <NSCoding>{
NSString *name;
int magicNumber;
float shoseSize;
NSMutableArray *subThingies;
}
@property (copy) NSString *name;
@property int magicNumber;
@property float shoseSize;
@property (retain) NSMutableArray *subThingies;
 
-(id) initwithName:(NSString *) n
  magicNumber:(int) mn shoseSize:(float) ss;
 
@end
 
 
 
//  codeObj.m
//  encodeObject
//
//  Created by 110 on 10-2-6.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//
 
#import "codeObj.h"
 
 
@implementation codeObj
 
@synthesize name;
@synthesize magicNumber;
@synthesize shoseSize;
@synthesize subThingies;
 
-(id) initwithName:(NSString *) n
  magicNumber:(int) mn shoseSize:(float) ss{
if(self=[super init]){
self.name=n;
self.magicNumber=mn;
self.shoseSize=ss;
self.subThingies=[NSMutableArray array];
}
return (self);
}
 
-(void) dealloc{
[name release];
[subThingies release];
[super dealloc];
}
//nscoding协议的方法
-(void) encodeWithCoder:(NSCoder *) coder{
[coder encodeObject:name forKey:@"name"];
[coder encodeInt:magicNumber forKey:@"magicNumber"];
[coder encodeFloat:shoseSize forKey:@"shoseSize"];
[coder encodeObject:subThingies forKey:@"subThingies"];
}
 
-(id) initWithCoder:(NSCoder *)  decoder{
if(self =[super init]){
self.name=[decoder decodeObjectForKey:@"name"];
self.magicNumber=[decoder decodeIntForKey:@"magicNumber"];
self.shoseSize=[decoder decodeFloatForKey:@"shoseSize"];
self.subThingies=[decoder decodeObjectForKey:@"subThingies"];
}
return (self);
}
 
-(NSString *) description{
NSString *descripton=[NSString stringWithFormat:@"%@:%d,%.1f,%@",name,magicNumber,
shoseSize,subThingies];
return (descripton);
}
 
 
@end
 
#import "codeObj.h"
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
codeObj *thing;
thing=[[[codeObj alloc] initwithName:@"name" magicNumber:20 shoseSize:30.5] autorelease];
NSLog(@"--------%@",thing);
NSData *freezeDrid;
freezeDrid=[NSKeyedArchiver archivedDataWithRootObject:thing];
[freezeDrid writeToFile:@"/tmp/codeobj.txt" atomically:YES];
codeObj *anotherThing;
anotherThing=[[[codeObj alloc] initwithName:@"ssssss" magicNumber:20 shoseSize:4.5] autorelease];
[anotherThing.subThingies addObject:thing];
 
NSData *other;
other=[NSKeyedArchiver archivedDataWithRootObject:anotherThing];
//写入文件
[other writeToFile:@"/tmp/objandobj.txt" atomically:YES];
//从文件中读取
NSData *fileData;
fileData=[NSData dataWithContentsOfFile:@"/tmp/objandobj.txt"];
codeObj *fromFile;
fromFile=[NSKeyedUnarchiver unarchiveObjectWithData:fileData];
NSLog(@"------%@",fromFile);
    [pool drain];
    return 0;
}

读后感:在自己的类中实现NScoding协议作用是使自己的类支持“由类转换到NSData”的功能(仅是添加支持)。而真正实现此功能的是 NSKeyedUnarchiver的unarchiveObjectWithData和NSKeyedArchiver的 archivedDataWithRootObje

ct。(类到NSData的转化)