iOS 歸檔、NSCoding協議

一、歸檔介紹

1.歸檔是將數據持久化的一種方式,一般針對于比較復雜對象,比如自定義的對象,來進行數據持久化操作。

2.歸檔的對象需要遵循NSCoding協議,存儲的時候調用encodeWithCoder:方法,讀取的時候調用initWithCoder:方法。

3.將數據寫入本地需要調用 [NSKeyedArchiver archiveRootObject:per toFile:filePath],filePath為存儲的路徑。

4.從本地讀取數據需要調用[NSKeyedUnarchiver unarchiveObjectWithFile:filePath],filePath為存儲的路徑。

二、對自定義對象進行歸檔

1.自定義Person類服從NSCoding協議

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface Person : NSObject <NSCoding>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) int age;
@property (nonatomic, assign)  CGFloat height;
@end

2.實現協議方法encodeWithCoder:和initWithCoder:

#import "Person.h"

@implementation Person
//寫入文件時調用 -- 將需要存儲的屬性寫在里面
- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeInt:self.age forKey:@"age"];
    [aCoder encodeFloat:self.height forKey:@"height"];
}

//從文件中讀取時調用 -- 將需要存儲的屬性寫在里面
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super init]) {
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.age = [aDecoder decodeIntForKey:@"age"];
        self.height = [aDecoder decodeFloatForKey:@"height"];
    }
    return self;
}
@end

3.寫入與讀取
寫入:[NSKeyedArchiver archiveRootObject:per toFile:filePath]
讀?。?[NSKeyedUnarchiver unarchiveObjectWithFile:filePath]

#import "ViewController.h"
#import "Person.h"
@interface ViewController ()

@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    [self saveModel];
    [self readModel];
}

//存儲數據
- (void)saveModel {
    Person *per = [Person new];
    per.name = @"xiaoming";
    per.age = 18;
    per.height = 180;
    
    NSString *filePath = [self getFilePath];
    
    //將對象per寫入
    [NSKeyedArchiver archiveRootObject:per toFile:filePath];
    
}
//讀取數據
- (void)readModel {
    NSString *filePath = [self getFilePath];
    
    //取出per對象
    Person *per = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    NSLog(@"%@ -- %@ -- %d -- %.0f", per, per.name, per.age, per.height);
}
//獲得全路徑
- (NSString *)getFilePath {
    //獲取Documents
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    //在Documents下創(chuàng)建Person.data文件
    NSString *filePath = [doc stringByAppendingPathComponent:@"Person.data"];
    return filePath;
}
@end

readModel:方法中打印出存儲的per對象相關信息,則對自定義對象Person數據持久化成功

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容