iOS 對模型對象進行歸檔,ios模型對象歸檔

來源:互聯網
上載者:User

iOS 對模型對象進行歸檔,ios模型對象歸檔

歸檔是指一種形式的序列化,專門編寫用於儲存資料的任何對象都應該支援歸檔。使用對模型對象進行歸檔的技術可以輕鬆將複雜的對象寫入檔案,然後再從中讀取它們。

只要在類中實現的每個屬性都是標量或者都是遵循NSCoding協議的某個類的執行個體,你就可以對整個對象進行完全歸檔。大多數的Foundation和Cocoa Touch類 都遵NSCoding協議,所以對於有大多數類來說,歸檔不太難。

 

遵循NSCoding協議:

NSCoding聲明了兩個方法,

- (void)encodeWithCoder:(NSCoder *)aCoder;和- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder;

第一個是 將對象編碼到歸檔中,第二個則是對歸檔解碼,來建立一個對象。

在BIDFourLines中:

#import <Foundation/Foundation.h>@interface BIDFourLines : NSObject <NSCoding, NSCopying>@property (copy, nonatomic) NSArray *lines;@end

 

#import "BIDFourLines.h"static NSString * const kLinesKey = @"kLinesKey";@implementation BIDFourLines #pragma mark - Coding- (id)initWithCoder:(NSCoder *)aDecoder{    self = [super init];    if (self) {        self.lines = [aDecoder decodeObjectForKey:kLinesKey];    }    return self;}- (void)encodeWithCoder:(NSCoder *)aCoder;{    [aCoder encodeObject:self.lines forKey:kLinesKey];}#pragma mark - Copying- (id)copyWithZone:(NSZone *)zone;{    BIDFourLines *copy = [[[self class] allocWithZone:zone] init];    NSMutableArray *linesCopy = [NSMutableArray array];    for (id line in self.lines) {        [linesCopy addObject:[line copyWithZone:zone]];    }    copy.lines = linesCopy;    return copy;}@end

註:上面遵循了NSCopying協議,遵循NSCopying協議對於任何模型對象來說都是非常好的事情,NSCopying協議中,有一個copyWithZone方法,可以用來複製對象。

 

在BIDViewController中:

#import "BIDViewController.h"#import "BIDFourLines.h"static NSString * const kRootKey = @"kRootKey";@interface BIDViewController ()@property (strong, nonatomic) IBOutletCollection(UITextField) NSArray *lineFields;@end@implementation BIDViewController- (NSString *)dataFilePath{    NSArray *paths = NSSearchPathForDirectoriesInDomains(                                                         NSDocumentDirectory, NSUserDomainMask, YES);    NSString *documentsDirectory = [paths objectAtIndex:0];    return [documentsDirectory stringByAppendingPathComponent:@"data.archive"];}- (void)viewDidLoad{    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.    NSString *filePath = [self dataFilePath];    //如果存在歸檔    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {        NSData *data = [[NSMutableData alloc]                        initWithContentsOfFile:filePath];        NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]                                         initForReadingWithData:data];        //解檔        BIDFourLines *fourLines = [unarchiver decodeObjectForKey:kRootKey];                [unarchiver finishDecoding];                for (int i = 0; i < 4; i++) {            UITextField *theField = self.lineFields[i];            theField.text = fourLines.lines[i];        }    }        //後台通知    UIApplication *app = [UIApplication sharedApplication];    [[NSNotificationCenter defaultCenter]     addObserver:self     selector:@selector(applicationWillResignActive:)     name:UIApplicationWillResignActiveNotification     object:app];}//進入後台時 歸檔- (void)applicationWillResignActive:(NSNotification *)notification{    NSString *filePath = [self dataFilePath];    BIDFourLines *fourLines = [[BIDFourLines alloc] init];    fourLines.lines = [self.lineFields valueForKey:@"text"];    NSMutableData *data = [[NSMutableData alloc] init];    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]                                 initForWritingWithMutableData:data];    [archiver encodeObject:fourLines forKey:kRootKey];    [archiver finishEncoding];    [data writeToFile:filePath atomically:YES];}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.