ios中 继承对象模型的归档实现


之前项目中使用到了归档的技术,也用到了MJExtension

但是问题是,这个公共库遇到了无法归档的一些问题,让人蛋疼不已,怎么办呢。

对于不能归档的部分,职能手动归档,很是无语。


查找了一下原因:

原来对于两个模型,如何A继承了B,那么A有很大的情况是无法归档的!


自己写了。

对于上述的A模型和B模来说,定义如下:

#import <Foundation/Foundation.h>
#import "Student.h"

@interface Coder : NSObject


@property (nonatomic,copy) NSString *text;
@property (nonatomic,copy) NSString *userName;
@property (nonatomic,copy) NSString *classId;
@property (nonatomic,strong) Student *stu;

@end


它的归档要写成如下形式:

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:_classId forKey:@"classId"];
    [aCoder encodeObject:_userName forKey:@"userName"];
    [aCoder encodeObject:_text forKey:@"text"];
    [aCoder encodeObject:_stu forKey:@"stu"];
    
}

- (id)initWithCoder:(NSCoder *)aDecoder // NS_DESIGNATED_INITIALIZER
{
    _classId = [aDecoder decodeObjectForKey:@"classId"];
    _userName = [aDecoder decodeObjectForKey:@"userName"];
    _text = [aDecoder decodeObjectForKey:@"text"];
    _stu = [aDecoder decodeObjectForKey:@"stu"];
    
    return self;
}




B模型定义如下:

#import "Coder.h"

@interface CoderChild : Coder


@property (nonatomic, strong) NSString *king;
@property (nonatomic, strong) NSString *father;
@end

它的归档则要写成如下的形式:

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [super encodeWithCoder:aCoder];
    [aCoder encodeObject:_king forKey:@"king"];
    [aCoder encodeObject:_father forKey:@"father"];
}


- (id)initWithCoder:(NSCoder *)aDecoder // NS_DESIGNATED_INITIALIZER
{
    unsigned int count = 0;
    self = [super initWithCoder:aDecoder];
    if (self) {
        _king = [aDecoder decodeObjectForKey:@"king"];
        _father = [aDecoder decodeObjectForKey:@"father"];
    }
    return self;
}


以上两个类,子类要调用父类的 initwithCoder方法

否则负类中的属性就无法被归档




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值