//存儲沒有實現NSCoding協議的數據/
//可以直接寫入文件的:字符串,數組,字典,(基本數據類型轉化為number對象)number二進制數據
//序列化(存儲):需要存儲沒有實現NSCoding協議的對象類型,需要先把對象序列化為二進制數據然后再把二進制數據寫入文件
//反序列化(讀取) :先從文件中讀取出二進制數據然后對二進制數據進行反序列為對應的類型
在模型的類中.m
在模型的類中導入NSCoding并聲明屬性.h并
@interface People :NSObject
@property (nonatomic,copy) NSString * name;
@property (nonatomic,assign) int age;
在模型的類中.m
//編碼協議序列化
- (void)encodeWithCoder:(NSCoder*)aCoder {
//使用編碼器aCoder對屬性進行編碼
[aCoder encodeInt:_age forKey:@"nine"];
//可以使用對應類型的編碼方法
[aCoder encodeObject:_name forKey:@"mingzi"];
}
//解碼協議反序列化
- (id)initWithCoder:(NSCoder *)aDecoder {
//判斷父類是否調用了init方法
if(self= [super init]) {
//使用解碼器aDecoder對屬性進行解碼
self.age=? [aDecoder decodeIntForKey:@"nine"];
self.name= [aDecoder decodeObjectForKey:@"mingzi"];
//? ? ? ? [aDecoder decodeIntForKey:@"nine"];
//? ? ? ? [aDecoder decodeObjectForKey:@"mingzi"];
}
return self;
}
//在viewDidLoad中
- (void)viewDidLoad {
[super viewDidLoad];
//初始化存放people對象的數組
NSMutableArray * array = [NSMutableArray array];
//找存儲位置
NSString * FilePath = [self getFilePath];
for(int i = 0; i < 3; i ++) {
People * p = [[People alloc] init];
p.name= [NSString stringWithFormat:@"%d-name",i];
p.age= i + 20;
[array addObject:p];
NSLog(@"%@",p.name);
NSLog(@"%d",p.age);
}
//序列化為二進制數據
NSData * data = [NSKeyedArchiver archivedDataWithRootObject:array];
//寫入文件
[data writeToFile:FilePath atomically:YES];
NSLog(@"%@",FilePath);
//傳參讀取數據
[self getDataWith:FilePath];
}
-(void)getDataWith:(NSString*)path {
//根據文件路徑讀取二進制數組
NSData *data = [NSData dataWithContentsOfFile:path];
NSMutableArray * array = [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSLog(@"%@",array);
People *p = array[1];
NSLog(@"%@",p.name);
}
- (NSString *)getFilePath {
NSString *homeFilePath =NSHomeDirectory();
NSString *FilePath = [homeFilePath stringByAppendingString:@"/Documents/arrayFilePath.plist"];
return FilePath;
}