一、創建一個類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
@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;
}