先新建一个person类:
@interface person : NSObject
{
NSString *name;
NSString *profession;
}
@property (nonatomic,copy)NSString *name;
@property (nonatomic,copy)NSString *profession;
@end
//implementation
#import "person.h"
@implementation person
@synthesize profession,name;
- (id)init
{
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:name forKey: @"kname"];
[aCoder encodeObject:profession forKey: @"kProfession"];
// [aCoder encodeObject:Age forKey: kAge];
// [aCoder encodeObject:marry forKey:kMarry];
}
- (id)initWithCoder:(NSCoder *)aDecoder{
if(self = [super init]){
self.name = [aDecoder decodeObjectForKey:@"kname"];
self.profession = [aDecoder decodeObjectForKey:@"kProfession"];
//Age = [aDecoder decodeObjectForKey:kAge];
// marry=[aDecoder decodeObjectForKey:kMarry];
}
return self;
}
#pragma mark ---------------NSCopying 1 method-------------
- (id)copyWithZone:(NSZone *)zone{
person *tmp = [[[self class] allocWithZone:zone] init];
tmp.name = [self.name copy];
tmp.profession = [self.profession copy];
return nil;
}
- (void)dealloc
{
[name release];
[profession release];
[super dealloc];
}
@end
//------------------------下面是调用方法
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[self processObjectWrite];
[self processObjectRead];
[self.window makeKeyAndVisible];
return YES;
}
-(NSString*)pathFileForProcess:(NSString *)pathName{
NSArray *directory=NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
return [[directory objectAtIndex:0] stringByAppendingPathComponent:pathName];
}
-(void)processObjectWrite{
person *pObject= [[person alloc] init];
pObject.name = [[NSString alloc] initWithString:@"wenQiang"];
pObject.profession = [[NSString alloc] initWithString:@"project manager"];
//[pObject setAge:24 andMarry: NO];
//NSMutableArray *testData = [[NSMutableArray alloc] init];
NSMutableData *data=[[NSMutableData alloc] init];
NSKeyedArchiver *archiver=[[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:pObject forKey:@"kObject"];
[archiver finishEncoding];
Boolean bWrite = [data writeToFile:[self pathFileForProcess:@"object2"] atomically:YES];
if(bWrite) NSLog(@"ok..."); else NSLog(@"write error!");
// [archiver release];
//[pObject release];
}
//归档读
-(void)processObjectRead{
NSMutableData *data = [[NSMutableData alloc] initWithContentsOfFile:[self pathFileForProcess:@"object2"]];
NSLog(@"data %@..", data);
NSKeyedUnarchiver *unchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
person *tmp = [unchiver decodeObjectForKey:@"kObject"];
[unchiver finishDecoding];
NSLog(@"OBJECT: name: %@ profession: %@", tmp.name, tmp.profession);
// [unchiver release];
//[tmp release];
}