ios中 繼承物件模型的歸檔實現

來源:互聯網
上載者:User

ios中 繼承物件模型的歸檔實現

 

之前項目中使用到了歸檔的技術,也用到了MJExtension

但是問題是,這個公用庫遇到了無法歸檔的一些問題,讓人蛋疼不已,怎麼辦呢。

對於不能歸檔的部分,職能手動歸檔,很是無語。

 

尋找了一下原因:

原來對於兩個模型,如何A繼承了B,那麼A有很大的情況是無法歸檔的!

 

自己寫了。

對於上述的A模型和B模來說,定義如下:

 

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

 

否則負類中的屬性就無法被歸檔

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.