//存儲(chǔ)沒有實(shí)現(xiàn)NSCoding協(xié)議的數(shù)據(jù)/
//可以直接寫入文件的:字符串鉴腻,數(shù)組酪碘,字典,(基本數(shù)據(jù)類型轉(zhuǎn)化為number對象)number二進(jìn)制數(shù)據(jù)
//序列化(存儲(chǔ)):需要存儲(chǔ)沒有實(shí)現(xiàn)NSCoding協(xié)議的對象類型尚洽,需要先把對象序列化為二進(jìn)制數(shù)據(jù)然后再把二進(jìn)制數(shù)據(jù)寫入文件
//反序列化(讀取) :先從文件中讀取出二進(jìn)制數(shù)據(jù)然后對二進(jìn)制數(shù)據(jù)進(jìn)行反序列為對應(yīng)的類型
在模型的類中.m
在模型的類中導(dǎo)入NSCoding并聲明屬性.h并
@interface People :NSObject
@property (nonatomic,copy) NSString * name;
@property (nonatomic,assign) int age;
在模型的類中.m
//編碼協(xié)議序列化
- (void)encodeWithCoder:(NSCoder*)aCoder {
//使用編碼器aCoder對屬性進(jìn)行編碼
[aCoder encodeInt:_age forKey:@"nine"];
//可以使用對應(yīng)類型的編碼方法
[aCoder encodeObject:_name forKey:@"mingzi"];
}
//解碼協(xié)議反序列化
- (id)initWithCoder:(NSCoder *)aDecoder {
//判斷父類是否調(diào)用了init方法
if(self= [super init]) {
//使用解碼器aDecoder對屬性進(jìn)行解碼
self.age=? [aDecoder decodeIntForKey:@"nine"];
self.name= [aDecoder decodeObjectForKey:@"mingzi"];
//? ? ? ? [aDecoder decodeIntForKey:@"nine"];
//? ? ? ? [aDecoder decodeObjectForKey:@"mingzi"];
}
return self;
}
//在viewDidLoad中
- (void)viewDidLoad {
[super viewDidLoad];
//初始化存放people對象的數(shù)組
NSMutableArray * array = [NSMutableArray array];
//找存儲(chǔ)位置
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);
}
//序列化為二進(jìn)制數(shù)據(jù)
NSData * data = [NSKeyedArchiver archivedDataWithRootObject:array];
//寫入文件
[data writeToFile:FilePath atomically:YES];
NSLog(@"%@",FilePath);
//傳參讀取數(shù)據(jù)
[self getDataWith:FilePath];
}
-(void)getDataWith:(NSString*)path {
//根據(jù)文件路徑讀取二進(jìn)制數(shù)組
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;
}