码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2015-06-24 19:13:02      阅读:156      评论:0      收藏:0      [点我收藏+]

标签: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中 继承对象模型的归档实现

标签:ios   继承   对象   归档   

原文地址:http://blog.csdn.net/j_akill/article/details/46622067

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!