- (void)viewDidLoad {
[super viewDidLoad];
#pragma mark ---写入字符串--------
//第一步:确定要存储文件夹的路径
NSString *documentPathStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
//第二步:确定要存储的数据 初始化一个字符串
NSString *str = @"Hello world";
//第三步:确定存放文件的路径,路径的终点是要存储数据的文件
NSString *strPath = [documentPathStr stringByAppendingPathComponent:@"str.txt"];
//第四步:写入文件(创建文件写入文件)
//atomically:YES:写入过程中断电时,会自动保存
[str writeToFile:strPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@",documentPathStr);
#pragma mark ---写入数组--------
//第二步:准备存储的数据
NSArray *arr = @[@"A",@"B"];
//第三步:存放位置
NSString *arrayPath = [documentPathStr stringByAppendingPathComponent:@"array.plist"];
//第四步:写入
[arr writeToFile:arrayPath atomically:YES];
#pragma mark ---写入字典--------
NSDictionary *dic = @{@"1":@"A",@"2":@"B"};
NSString *dicPath = [documentPathStr stringByAppendingPathComponent:@"dic.plist"];
[dic writeToFile:dicPath atomically:YES];
#pragma mark ---读取--------
//通过路径读取数据,使用StringWithContentsOfFile方法,在读取的时候,第一个参数表示读取文件的路径,第二个参数表示编码格式,第三个表示错误信息
NSString *newStr = [NSString stringWithContentsOfFile:strPath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@",newStr);
NSArray *newArray = [NSArray arrayWithContentsOfFile:arrayPath];
NSLog(@"%@",newArray);
#pragma mark ---图片--------
//根据ImageNamed获取图片(会在缓存中存储一份,下次再获取同名图片的话直接从缓存中取出) 优点:快 只有第一次时慢 缺点:会浪费内存,如果只用一次的话这块内存就会浪费掉了
//UIImage *image = [UIImage imageNamed:@"1"];
//根据ContentOfFile获取图片:每一次都会从路径中读取,不会占用内存.如果该图片只使用一次的话 推荐使用ContentOfFile
//UIImage *image1 = [[UIImage alloc] initWithContentsOfFile:@"1"];
UIImage *image = [UIImage imageNamed:@"1"];
#pragma mark ---将UIImage类型对象转化成NSData类型---
//NSData *data = UIImagePNGRepresentation(image);
//第一个参数:表示转哪个UIImage类型的对象
//第二个参数:压缩系数 越小压缩的越厉害
NSData *data = UIImageJPEGRepresentation(image, 1);
NSString *dataPath = [documentPathStr stringByAppendingPathComponent:@"data.png"];
[data writeToFile:dataPath atomically:YES];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[self.view addSubview:imageView];
#pragma mark ---将类型NSData对象转化成UIImage类型---
NSData *newData = [NSData dataWithContentsOfFile:dataPath];
UIImage *newImage = [[UIImage alloc] initWithData:newData];
NSLog(@"%@",newImage);
}
@end
UI-senior(数据本地化-简单对象的写入)
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- pragma mark ------- * 简单的文件读写 ------ ios提供四种类型可以直接进行文件...
- 首先说明归解档是一种编码方式,不是数据本地化的方式,在复杂对象写入本地的时候实际上使用的还是writeToFile...
- (1)初次见面,再也不见 “你好,我是沈言” “你好,谢言希” “……” 气氛有些尴尬,咖啡厅里传来钢琴发出的声音...