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方法
否則負類中的屬性就無法被歸檔