- @interface MyTest : NSObject <NSCoding>{
- NSString *name;
- int number;
- NSMutableArray *array;
- }
- @property (nonatomic ,copy)NSString *name;
- @property (nonatomic ,assign)int number;
- @property (nonatomic ,retain)NSMutableArray *array;
- @end
- #import "MyTest.h"
- #import "Test1.h"
- @implementation MyTest
- @synthesize name;
- @synthesize number;
- @synthesize array;
- - (id)init {
- if (self = [super init]) {
- array = [[NSMutableArray alloc] initWithCapacity:4];
- for (int i = 0; i<4; i++) {
- Test1 *test = [[Test1 alloc] init];
- test.testName = @"pb";
- [array addObject:test];
- [test release];
- }
- }
- return self;
- }
- - (void)encodeWithCoder:(NSCoder *)aCoder {
- [aCoder encodeObject:name forKey:@"name"];
- [aCoder encodeInt:number forKey:@"number"];
- [aCoder encodeObject:array forKey:@"array"];
- }
- - (id)initWithCoder:(NSCoder *)aDecoder {
- if (self = [super init]) {
- self.name = [aDecoder decodeObjectForKey:@"name"];
- self.number = [aDecoder decodeIntForKey:@"number"];
- self.array = [aDecoder decodeObjectForKey:@"array"];
- }
- return self;
- }
- @end
- @interface Test1 : NSObject <NSCoding>{
- NSString *testName;
- }
- @property (nonatomic,copy)NSString *testName;
- @end
- @implementation Test1
- @synthesize testName;
- - (void)encodeWithCoder:(NSCoder *)aCoder {
- [aCoder encodeObject:testName forKey:@"testname"];
- }
- - (id)initWithCoder:(NSCoder *)aDecoder {
- if (self = [super init]) {
- self.testName = [aDecoder decodeObjectForKey:@"testname"];
- }
- return self;
- }
- @end
- MyTest *test = [[MyTest alloc] init];
- test.name = @"pubo";
- test.number = 1;
- NSData *data = [NSKeyedArchiver archivedDataWithRootObject:test];
- [data writeToFile:@"/abc.txt" atomically:YES];
- NSData *data2 = [NSData dataWithContentsOfFile:@"/abc.txt"];
- MyTest *test2 = [NSKeyedUnarchiver unarchiveObjectWithData:data2];
- NSLog(@"test.name:%@",test2.name);
- NSLog(@"test.number:%d",test2.number);
- NSArray *array = test2.array;
- for (Test1 *test in array) {
- NSLog(@"test1 name:%@",test.testName);
- }