使用NSData读写多个对象
#import <Foundation/Foundation.h>
#import "MyClass.h"
#import "MyClass1.h"
// 对象的编码和解码(序列化和反序列化)
int main(int argc, const char * argv[]) {
@autoreleasepool {
#warning 使用NSData读写多个对象
NSMutableData *data;
data = [NSMutableData data];//初始化NSMutableData
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];//初始化NSKeyedArchiver
MyClass1 *my2 = [[MyClass1 alloc]init];
my2.value = 123;
[archiver encodeObject:my forKey:@"myClass"];
[archiver encodeObject:my2 forKey:@"myClass1"];
[archiver finishEncoding];
if([data writeToFile:@"two_objects" atomically:YES] == YES)
{
NSLog(@"两个对象存储成功.");
}
// 恢复MyClass和MyClass1
NSData *data1;
data1 = [NSData dataWithContentsOfFile:@"two_objects"];
if(!data1)
{
NSLog(@"不能读取两个对象.");
return 1;
}
NSKeyedUnarchiver *twoObjects;
twoObjects = [[NSKeyedUnarchiver alloc]initForReadingWithData:data1];
MyClass *myClass = [twoObjects decodeObjectForKey:@"myClass"];
MyClass1 *myClass1 = [twoObjects decodeObjectForKey:@"myClass1"];
[twoObjects finishDecoding];
NSLog(@"myClass.email = %@", myClass.email);//myClass.email = bill@microsoft.com
NSLog(@"myClass1.value = %d", myClass1.value);//myClass1.value = 123
}
return 0;
}
#import <Foundation/Foundation.h>
@interface MyClass1 : NSObject<NSCoding>
@property int value;
@end
#import "MyClass1.h"
@implementation MyClass1
@synthesize value;
// 编码
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:[NSNumber numberWithInt:value] forKey:@"key_value"];
}
// 解码
-(id)initWithCoder:(NSCoder *)aDecoder
{
value = [[aDecoder decodeObjectForKey:@"key_value"] intValue];
return self;
}
@end
#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