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方法

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




你可能感兴趣的:(ios,继承,对象,归档)