#import <Foundation/Foundation.h>
#import "MyClass.h"
#import "MyClass1.h"
// 对象的编码和解码(序列化和反序列化)
int main(int argc, const char * argv[]) {
@autoreleasepool {
MyClass *my = [[MyClass alloc]init];
my.name = @"bill";
my.email=@"bill@microsoft.com";
if([NSKeyedArchiver archiveRootObject:my toFile:@"myclass.arch"] == YES)//存储对象
{
NSLog(@"文件存储成功.");
}
MyClass *my1;
my1 = [NSKeyedUnarchiver unarchiveObjectWithFile:@"myclass.arch"];
NSLog(@"my1.name = %@, my1.email = %@", my1.name, my1.email);//my1.name = bill, my1.email = bill@microsoft.com
}
#import <Foundation/Foundation.h>
@interface MyClass : NSObject<NSCopying,NSCoding>
@property (copy, nonatomic) NSString *name, *email;
@end
#import "MyClass.h"
@implementation MyClass
@synthesize name, email;
-(id)copyWithZone:(NSZone *)zone
{
MyClass* my = [[MyClass allocWithZone:zone]init];
my.name = name;
my.email = email;
return my;
}
// 编码
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:name forKey:@"key_name"];
[aCoder encodeObject:email forKey:@"key_email"];
}
// 解码
-(id)initWithCoder:(NSCoder *)aDecoder
{
name = [aDecoder decodeObjectForKey:@"key_name"];
email = [aDecoder decodeObjectForKey:@"key_email"];
return self;
}
@end
网友评论