IOS資料持久化之歸檔NSKeyedArchiver,iosnskeyedarchiver
IOS資料持久化的方式分為三種:
下面主要來介紹一個歸檔NSKeyedArchiver。
歸檔(又名序列化),把對象轉為位元組碼,以檔案的形式儲存到磁碟上;程式運行過程中或者當再次重寫開啟程式的時候,可以通過解歸檔(還原序列化)還原這些對象。
歸檔方式:
- 對Foundation架構中對象進行歸檔
- 對自訂的內容進行歸檔
- 對自訂的對象進行歸檔
<一> 對Foundation架構中對象進行歸檔
//獲得檔案路徑 NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *filePath = [documentPath stringByAppendingPathComponent:@"file.archiver"]; //歸檔(序列化)NSArray *archiveAry = @[@"jereh",@"ios"];if ([NSKeyedArchiver archiveRootObject: archiveAry toFile:filePath]) { NSLog(@"Archiver success");} //解歸檔(還原序列化)NSArray *unArchiveAry = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];NSLog(@"%@",unArchiveAry);
小結:
<二> 對自訂的內容進行歸檔
//獲得檔案路徑NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];NSString *filePath = [documentPath stringByAppendingPathComponent:@"file.archiver"]; //1. 使用NSData存放歸檔資料NSMutableData *archiverData = [NSMutableData data];//2. 建立歸檔對象NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:archiverData];//3. 添加歸檔內容 (設定索引值對) [archiver encodeObject:@"jereh" forKey:@"name"]; [archiver encodeInt:20 forKey:@"age"]; [archiver encodeObject:@[@"ios",@"oc"] forKey:@"language"];//4. 完成歸檔 [archiver finishEncoding];//5. 將歸檔的資訊儲存到磁碟上if ([archiverData writeToFile:filePath atomically:YES]) { NSLog(@"archiver success");} //解歸檔//1. 從磁碟讀取檔案,產生NSData執行個體NSData *unarchiverData = [NSData dataWithContentsOfFile:filePath];//2. 根據Data執行個體建立和初始化解歸檔對象NSKeyedUnarchiver *unachiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:unarchiverData];//3. 解歸檔,根據key值訪問NSString *name = [unachiver decodeObjectForKey:@"name"];int age = [unachiver decodeIntForKey:@"age"];NSArray *ary = [unachiver decodeObjectForKey:@"language"];NSLog(@"name=%@ age=%i ary=%@",name,age,ary);
小結:
<三> 對自訂的對象進行歸檔
#define IDNUM @"idNum"#define NAME @"name"@interface Student : NSObject <NSCoding>@property (nonatomic, assign) int idNum;@property (nonatomic, copy) NSString *name;@end@implementation Student#pragma mark 編碼 對對象屬性進行編碼的處理- (void)encodeWithCoder:(NSCoder *)aCoder{ [aCoder encodeInt:_idNum forKey:IDNUM]; [aCoder encodeObject:_name forKey:NAME];}#pragma mark 解碼 解碼歸檔資料來初始化對象- (id)initWithCoder:(NSCoder *)aDecoder{ if (self = [super init]) { _idNum = [aDecoder decodeIntForKey:IDNUM]; _name = [aDecoder decodeObjectForKey:NAME]; } return self;}@end
小結:
-
- encodeWithCoder方法對對象屬性進行編碼,在對象歸檔時調用
- initWithCoder方法解碼歸檔資料來初始化對象,在對象解歸檔時調用
總結: