忘記出自哪里了:
如果對象是NSString媳禁、NSDictionary、NSArray画切、NSData竣稽、NSNumber等類型,可以直接用NSKeyedArchiver進行歸檔和恢復(fù)
不是所有的對象都可以直接用這種方法進行歸檔霍弹,只有遵守了NSCoding協(xié)議的對象才可以
NSCoding協(xié)議有2個方法:
encodeWithCoder:
每次歸檔對象時毫别,都會調(diào)用這個方法。一般在這個方法里面指定如何歸檔對象中的每個實例變量典格,可以使用encodeObject:forKey:方法歸檔實例變量
initWithCoder:
每次從文件中恢復(fù)(解碼)對象時岛宦,都會調(diào)用這個方法。一般在這個方法里面指定如何解碼文件中的數(shù)據(jù)為對象的實例變量耍缴,可以使用decodeObject:forKey方法解碼實例變量
歸檔系統(tǒng)自帶類:
NSArray * array = [NSArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5", nil];
NSString * path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString * filePath = [path stringByAppendingPathComponent:@"bbb.xx"];
[NSKeyedArchiver archiveRootObject:array toFile:filePath];
NSArray * arrays = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"dict = %@",arrays);
歸檔自定義類:
Others * others = [[Others alloc] init];
others.name = @"小明";
others.age = @"20";
NSString * parh = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString * filePath = [parh stringByAppendingPathComponent:@"cccc.xxx"];
[NSKeyedArchiver archiveRootObject:others toFile:filePath];
Others * other = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"name = %@, age = %@",other.name,others.age);
Other.h
#import <Foundation/Foundation.h>
@interface Others : NSObject
@property (strong , nonatomic) NSString * name;
@property (strong , nonatomic) NSString * age;
@end
Other.m
#import "Others.h"
//NSKeyedArchiver歸檔如果想將一個自定義對象保存到文件中必須實現(xiàn)NSCoding協(xié)議
@interface Others ()<NSCoding>
@end
@implementation Others
//當(dāng)從文件中讀取一個對象的時候就會調(diào)用該方法
//也在該方法中說明如何讀取儲存在文件中的對象
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super init];
if (self) {
self.name = [coder decodeObjectForKey:@"name"];
self.age = [coder decodeObjectForKey:@"age"];
}
return self;
}
//將一個自定義對象保存到文件的時候就會調(diào)用該方法
//也在該方法中說明如何儲存自定義對象的屬性
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeObject:self.age forKey:@"age"];
}
@end