UI-senior(数据本地化-简单对象的写入)

- (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(数据本地化-简单对象的写入))