標籤:
歸檔:是對對象及其屬性還有同其他對象間的關係進行編碼,形成一個文檔,該文檔既可以儲存於檔案系統,也可以在進程或網路間傳送。
歸檔過程把對象圖儲存為一種與架構無關的位元組流,保持對象的標識以及對象間的關係。
能夠歸檔的對象必須遵守NSCoding協議,實現以下方法:
- (void)encodeWithCoder:(NSCoder *)aCoder;- (id)initWithCoder:(NSCoder *)aDecoder;
使用NSCoder對象進行編碼與解碼操作。NSCoder本身是抽象類別,實際運行中使用NSKeyedArchiver和NSKeyedUnarchiver這兩個具體類,也就是使用基於鍵的歸檔技術。
Archiving:
+ (BOOL)archiveRootObject:(id)rootObject toFile:(NSString *)path;
Unarchiving:
+ (id)unarchiveObjectWithFile:(NSString *)path;
樣本:
//// NimoPerson.h// TestDemo//// Created by fu zheng on 15/8/13.// Copyright (c) 2015年 FuZheng. All rights reserved.//#import <Foundation/Foundation.h>@interface NimoPerson : NSObject <NSCoding>@property (nonatomic, copy) NSString *name;@property (nonatomic, copy) NSString *gender;@property (nonatomic, assign) NSUInteger age;@property (nonatomic, retain) NSSet *friends;@property (nonatomic, getter = isMarried) BOOL married;@end
//// NimoPerson.m// TestDemo//// Created by fu zheng on 15/8/13.// Copyright (c) 2015年 FuZheng. All rights reserved.//#import "NimoPerson.h"@implementation NimoPerson- (void)encodeWithCoder:(NSCoder *)aCoder{ [aCoder encodeObject:self.name forKey:@"name"]; [aCoder encodeObject:self.gender forKey:@"gender"]; [aCoder encodeInteger:self.age forKey:@"age"]; [aCoder encodeObject:self.friends forKey:@"friends"]; [aCoder encodeBool:[self isMarried] forKey:@"married"]; }- (id)initWithCoder:(NSCoder *)aDecoder{ if (self = [super init]) { _name = [[aDecoder decodeObjectForKey:@"name"] copy]; _gender = [[aDecoder decodeObjectForKey:@"gender"] copy]; _age = [aDecoder decodeIntegerForKey:@"age"]; _friends = [aDecoder decodeObjectForKey:@"friends"]; _married = [aDecoder decodeBoolForKey:@"married"]; } return self;}- (id)init{ NSSet *friends = [[NSSet alloc] initWithArray:@[@"Tom", @"Jessica", @"Lily"]]; return [self initWithName:@"Tony" gender:@"male" age:28 friends:friends married:NO];}- (id)initWithName:(NSString *)name gender:(NSString *)gender age:(NSUInteger)age friends:(NSSet *)friends married:(BOOL)married{ if (self = [super init]) { _name = [name copy]; _gender = [name copy]; _age = age; _friends = friends; _married = married; } return self;}- (NSString *)description{ NSDictionary *desDic = @{@"name":_name, @"gender":_gender, @"age":[NSNumber numberWithInteger:_age], @"married":[NSNumber numberWithBool:_married]}; return [NSString stringWithFormat:@"%@", desDic];}@end
iOS資料持久化---對象歸檔