如果是自定义类型的归档和解档,是按以下步骤实现
如果不是自定义类型,直接第四步就可以。
一、创建一个类User
二、在User.h中遵循NSCoding协议
#import <Foundation/Foundation.h>
@interface User : NSObject<NSCoding>
{
int _userAge;//例子
NSString *_userName;//
}
@property(nonatomic,assign)int userAge;
@property(nonatomic,copy)NSString *userName;
@end
三、在User.m中实现协议中的归档,解档方法
@implementation User
@synthesize userName = _userName;
@synthesize userAge = _userAge;
// 实现归档操作
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:_userName forKey:@"username"];
[aCoder encodeInt:_userAge forKey:@"userage"];
}
// 实现解档操作
- (id)initWithCoder:(NSCoder *)aDecoder
{
_userAge = [aDecoder decodeIntForKey:@"userage"];
_userName = [aDecoder decodeObjectForKey:@"username"];
return self;
}
@end
四、在AppDelegate.m中包含user.h
#import "AppDelegate.h"
#import "User.h"
@implementation AppDelegate
@synthesize window=_window;
- (void)dealloc
{
[_window release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]autorelease];
// Override point for customization after application launch.
// 归档(序列化和反序列化) - 存储自定义对象
User *user = [[User alloc] init];
user.userAge = 30;
user.userName = @"张三";
// 归档操作(将归档数据写入NSMutableData中,然后将NSMutableData对象写成文件)
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
// 写入数据
[archiver encodeObject:@"test" forKey:@"username"];
[archiver encodeObject:@"123456" forKey:@"userpassword"];
[archiver encodeInt:111 forKey:@"number"];
[archiver encodeObject:user forKey:@"user"];
// 写入完毕
[archiver finishEncoding];
[archiver release];
// 将data写成文件
[data writeToFile:[NSStringstringWithFormat:@"%@/Library/Caches/user.archiver",NSHomeDirectory()] atomically:NO];
[data release];
// 解档(先把文件读取成NSMutableData然后从data中解出数据)
NSMutableData *contentData = [[NSMutableData alloc] initWithContentsOfFile:[NSStringstringWithFormat:@"%@/Library/Caches/user.archiver",NSHomeDirectory()]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:contentData];
int number = [unarchiver decodeIntForKey:@"number"];
NSString *username = [unarchiver decodeObjectForKey:@"username"];
NSString *userpassword = [unarchiver decodeObjectForKey:@"userpassword"];
User *contentUser = [unarchiver decodeObjectForKey:@"user"];
NSLog(@"user.userAge = %d",contentUser.userAge);
NSLog(@"user.userName = %@",contentUser.userName);
NSLog(@"number = %d",number);
NSLog(@"username = %@",username);
NSLog(@"userpassword = %@",userpassword);
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}