我是将聊天记录存到本地,里边用到了自定义的对象,把数据转成Data格式存到本地,在转Data格式的时候报错了,这时候需要先将自定义对象进行归档才可以转Data格式。方法如下:
一、在.h文件中声明协议
#import <Foundation/fountion.h>
@interface Person : NSObject <NSCoding>
@property (nonatomic,copy) NSString * name;
@property (nonatomic,copy) NSString * sex;
@property (nonatomic,copy) NSString * name1;
@property (nonatomic,copy) NSString * name2;
二、在.m文件中实现encodeWithCoder和intiWithCoder方法
#import "Person.h"
@implementation Person
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encoderObject:self.name forKey:@"name"];
[aCoder encoderObject:self.sex forKey:@"sex"];
[aCoder encoderObject:self.name1 forKey:@"name1"];
[aCoder encoderObject:self.name2 forKey:@"name2"];
}
-(id)initWithCoder:(NSCoder *)aDecoder{
if (self = [super init]) {
self.name = [aDecoder decodeObjecForKey:@"name"];
self.sex = [aDecoder decodeObjecForKey:@"sex"];
self.name1 = [aDecoder decodeObjecForKey:@"name1"];
self.name2= [aDecoder decodeObjecForKey:@"name2"];
}
return self;
}
归档之后就把对象存储到字典或数组里,转成Data格式的,再存储到本地即可。
//字典转data
+(NSData *)returnDataWithDictionary:(NSDictionary *)dict
{
NSMutableData * data = [[NSMutableData alloc] init];
NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:dict forKey:@"talkData"];
[archiver finishEncoding];
[data autorelease];
[archiver autorelease];
return data;
}
//路径文件转dictonary
+(NSDictionary *)returnDictionaryWithDataPath:(NSString *)path
{
NSData * data = [[NSMutableData alloc] initWithContentsOfFile:path];
NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSDictionary * myDictionary = [[unarchiver decodeObjectForKey:@"talkData"] retain];
[unarchiver finishDecoding];
// NSLog(@"%@", myDictionary);
[unarchiver autorelease];
[data autorelease];
return myDictionary;
}