我是將聊天記錄存到本地,裏邊用到了自定義的對象,把數據轉成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;
}