iOS - 保存自定义对象(姓名,性别.....)

我是将聊天记录存到本地,里边用到了自定义的对象,把数据转成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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值