数据持久化------Archiving(归档,解档)
其中TRPerson為自定義的繼承自NSObject的類的子類 ?其中有兩個屬性,name 和 age
.h文件
#import
?
@interface TRPerson : NSObject<</span>NSCoding>
@property (nonatomic,strong)NSString *name;
@property (nonatomic,strong)NSNumber * age;
//初始化方法
- (id)initWithName:(NSString*)name withAge:(NSNumber *)age;
?
@end
?
?
.m文件
#import "TRPerson.h"
?
@implementation TRPerson
- (id)initWithName:(NSString *)name withAge:(NSNumber *)age{
? ? if (self=[super init]) {
? ? ? ? self.age=age;
? ? ? ? self.name=name;
? ? }
? ? return? self;
?? ?
}
#pragma mark - NSCoding
?
?//對屬性進(jìn)行解碼(時機(jī):執(zhí)行encodeObject方法)
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
?? self= [super init];
? ? if (self) {
? ? ? ? self.name= [aDecoder decodeObjectForKey:@"name"];
? ? ? ? self.age=[aDecoder decodeObjectForKey:@"age"];
? ? }
? ? return self;
}
?
?
//對屬性進(jìn)行編碼的方法
- (void)encodeWithCoder:(NSCoder *)aCoder{
? ? [aCoder encodeObject:self.age forKey:@"age"];
? ? [aCoder encodeObject:self.name forKey:@"name"];
?? ?
}
- (NSString *)description{
? ? TRPerson *person=[[TRPerson alloc]initWithName:self.name withAge:self.age];
? ? return? [NSString stringWithFormat:@"name:%@ age:%@",person.name ,person.age];
}
?
@end
?
ViewController中的viewDidLoad方法中實(shí)現(xiàn)數(shù)據(jù)的歸檔和解擋
?- (void)viewDidLoad {
? ? [super viewDidLoad];
? ? //準(zhǔn)備工作
?? ? //將自定義的TRPerson對象進(jìn)行歸檔(寫)
?? ?
? ? TRPerson *person=[[TRPerson alloc]initWithName:@"張飛" withAge:@20];
? ? //Documents/archiving
? ? NSString *doumentsPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES).firstObject;
? ? NSString *archiverPath = [doumentsPath stringByAppendingPathComponent:@"archving"];
? ? //1.可變數(shù)據(jù)類型
? ? NSMutableData *data=[NSMutableData data];
? ? //2.歸檔對象
? ? NSKeyedArchiver *archiver=[[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
? ? //3.編碼
?? ?
? ? [archiver encodeObject:person forKey:@"person"];
? ? //4.編碼完成
? ? [archiver finishEncoding];
? ? //5.寫入文件
?? ?
? ? [data writeToFile:archiverPath atomically:YES];
? ? //將自定義的TRPerson對象進(jìn)行解擋(讀)
? ? //1.讀取數(shù)據(jù)
? ? NSData *readingData=[NSData dataWithContentsOfFile:archiverPath];
? ? //2.解碼對象
? ? NSKeyedUnarchiver *unArchiver=[[NSKeyedUnarchiver alloc]initForReadingWithData:readingData];
? ? //3.解碼
?TRPerson *personRead=[unArchiver decodeObjectForKey:@"person"];
? ? //4.完成解碼
? ? [unArchiver finishDecoding];
? ? //驗證
? ? NSLog(@"%@",personRead );
}
轉(zhuǎn)載于:https://www.cnblogs.com/zhao-jie-li/p/5128460.html
總結(jié)
以上是生活随笔為你收集整理的数据持久化------Archiving(归档,解档)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: web开发方法
- 下一篇: word2016打印怎么使用