NSCcoding是一個(gè)協(xié)議,基本上所有的原生的類都是實(shí)現(xiàn)了NSCoding協(xié)議,在歸檔的過程中進(jìn)行了轉(zhuǎn)碼,所以才可以歸檔成功。
@protocol NSCoding
- (void)encodeWithCoder:(NSCoder *)aCoder;
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder; // NS_DESIGNATED_INITIALIZER
@end
NSCcoding協(xié)議兩個(gè)必須實(shí)現(xiàn)的方法!
? 而且NSCoding多用于對(duì)自定義的類的實(shí)體對(duì)象進(jìn)行歸檔,比如寫一個(gè)student類
@interface Student : NSObject@property (nonatomic , retain) NSString *name;
@property (nonatomic , retain) NSString *ID;
-(Student *)initWithName : (NSString *)newName
and : (NSString *)newID;
@end
Student類需要實(shí)現(xiàn)協(xié)議NSCoding,.m文件中是這樣的:
@implementation Student
@synthesize name = _name,ID = _ID;
//初始化學(xué)生類
-(Student *)initWithName:(NSString *)newName and:(NSString *)newID{
self = [super init];
if (self) {
self.name = newName;
self.ID = newID;
}
return self;
}
//學(xué)生類內(nèi)部的兩個(gè)屬性變量分別轉(zhuǎn)碼
-(void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeObject:self.ID forKey:@"ID"];
}
//分別把兩個(gè)屬性變量根據(jù)關(guān)鍵字進(jìn)行逆轉(zhuǎn)碼,最后返回一個(gè)Student類的對(duì)象
-(id)initWithCoder:(NSCoder *)aDecoder{
if (self = [super init]) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.ID = [aDecoder decodeObjectForKey:@"ID"];
}
return self;
}
@end
自定義類Student實(shí)現(xiàn)了NSCoding協(xié)議以后,就可以進(jìn)行歸檔轉(zhuǎn)換了,具體實(shí)現(xiàn):
Student *stu1 = [[Student alloc]initWithName:@"124" and:@"111"];//學(xué)生對(duì)象stu1
Student *stu2 = [[Student alloc]initWithName:@"223" and:@"222"];//學(xué)生對(duì)象stu2
NSArray *stuArray = [NSArray arrayWithObjects:stu1,stu2, nil];//學(xué)生對(duì)象數(shù)組,里面包含stu1和stu2
NSData *stuData = [NSKeyedArchiver archivedDataWithRootObject:stuArray];//歸檔
NSLog(@"data = %@",stuData);
NSArray *stuArray2 = [NSKeyedUnarchiver unarchiveObjectWithData:stuData];//逆歸檔
NSLog(@"array2 = %@",stuArray2);
在IOS的開發(fā)中,小數(shù)據(jù)量的持久化都用NSUserDefaults來實(shí)現(xiàn),但是NSUserDefaults只能保存NSString, NSNumber, NSDate, NSArray, NSDictionary這些數(shù)據(jù)類型,但大多時(shí)候,我們會(huì)將一個(gè)對(duì)象實(shí)體做持久化的保存,由于不是大批量的數(shù)據(jù),不會(huì)用到sqlite,那么這個(gè)時(shí)候NSUserDefaults會(huì)是很好的選擇,其實(shí)對(duì)象類型可以通過NSCoding的委托方法來實(shí)現(xiàn)的。