#pragma mark 写入文件
//简单对象写入文件---------------->字符串、数组、字典、图片(才怪,是把图片转换成的NSData对象)
//1.字符串
NSString *incantation = @"yi hu shi ";
NSString *homePath = NSHomeDirectory();
homePath = [homePath stringByAppendingString:@"/hh.txt"];
//NO:不安全,会中断。
//AllowLossy允许丢失碎片。
//ExternalRepresentation按字节转换,一个字节也不能丢失。
[incantation writeToFile:homePath atomically:YES encoding:NSStringEncodingConversionExternalRepresentation error:nil];
NSLog(@"%@",homePath);
//从文件获取字符串
NSString *result = [NSString stringWithContentsOfFile:homePath encoding:NSStringEncodingConversionExternalRepresentation error:nil];
NSLog(@"%@",result);
//2、数组写入文件
NSArray *array = @[@"you",@"are",@"you"];
NSString *path = NSHomeDirectory();
path = [path stringByAppendingString:@"hitu"];
//写入
[array writeToFile:path atomically:YES];
NSLog(@"%@",path);
//读取
NSArray *resultArray = [NSArray arrayWithContentsOfFile:path];
NSLog(@"%@",resultArray);
//3、字典写入文件
NSDictionary *dictionary = @{
@"yiyi":@"huhu",
@"yoyo":@"kiki"
};
NSString *path = NSHomeDirectory();
path = [path stringByAppendingString:@"/oppo.txt"];
//写入
[dictionary writeToFile:path atomically:YES];
NSLog(@"%@",path);
//读取
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
NSLog(@"%@",dict);
//4、图片是以NSData写入文件
UIImage *image = [UIImage imageNamed:@"background.png"];
//0-1之间的,1是原封不动的大小
NSData *data = UIImageJPEGRepresentation(image, 0.5);
NSString *path = NSHomeDirectory();
path = [path stringByAppendingString:@"/image"];
//写入
[data writeToFile:path atomically:YES];
NSLog(@"%@",path);
//读取
NSData *resultData = [NSData dataWithContentsOfFile:path];
UIImage *resultImage = [UIImage imageWithData:resultData];
[_imageView setImage:resultImage];