#import <Foundation/Foundation.h>
@interface person :NSObject <NSCoding>
{
NSMutableString *name;
NSNumber *pid;
}
@property(copy) NSMutableString *name; //这用copy 就可以,使用其他的都会报错
@property(copy) NSNumber *pid; //这里用copy 就可以,使用其它的都会报错
-(void) encodeWithCoder:(NSCoder *)aCoder;
-(id) initWithCoder:(NSCoder *)aDecoder;
-(void) dealloc;
@end
@implementation person :NSObject
@synthesize name,pid;
-(void) encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:name forKey:@"person_name"];
[aCoder encodeObject:pid forKey:@"person_id"];
}
-(id) initWithCoder:(NSCoder *)aDecoder
{
name=[aDecoder decodeObjectForKey:@"person_name"];
pid=[aDecoder decodeObjectForKey:@"person_id"];
return self;
}
-(void) dealloc
{
[name dealloc];
[pid dealloc];
[super release]; //这为什么不直接dealloc呢?
}
@end
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
NSAutoreleasePool *pool=[NSAutoreleasePool new];
person *p=[person new];
[p autorelease];
p.pid=[NSNumber numberWithInt:1];
p.name=[NSMutableString stringWithString:@"liji"];
printf("name=%s,pid=%i\n",p.name.UTF8String,p.pid.intValue);
person *p2;
if([NSKeyedArchiver archiveRootObject:p toFile:@"test3.txt"])
{
printf("写出自定义类对象成功\n");
p2=[NSKeyedUnarchiver unarchiveObjectWithFile:@"test3.txt"];
if(p2!=nil)
{
[p2 autorelease];
printf("自定义对象读档成功\n");
printf("name=%s,pid=%i\n",p2.name.UTF8String,p2.pid.intValue); //这样运行时报错
}
p2.name=[NSMutableString stringWithString:@"zhangsan"];
printf("%s\n",p.name.UTF8String);
printf("%s\n",p2.name.UTF8String); //
}
else
printf("写出自定义类对象失败\n");
[pool drain];
}