zoukankan      html  css  js  c++  java
  • iOS笔记之文件读写

    最近做的项目中要存储一组图片数据,图片带有name,date等属性,处理办法是讲image图片直接存在沙盒documents文件中,再使用plist文件存储图片属性和image路径。

    存入图片:

    - (void)savePhotos:(NSArray *)photos {
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *plistPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"photo_info.plist"];
        NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Image"];
        NSLog(@"%@", filePath);
        
        NSFileManager* fileManager = [NSFileManager defaultManager];
        if (![fileManager fileExistsAtPath:plistPath]) {
            [fileManager createFileAtPath:plistPath contents:nil attributes:nil];
        }
        if (![fileManager fileExistsAtPath:filePath]) {
            [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:NO attributes:nil error:nil];
        }
    
        NSMutableArray *savePhotos = [[NSMutableArray alloc] init];
        
        for (Photo *photo in photos) {
            NSMutableDictionary *info = [[NSMutableDictionary alloc]init];
    
            NSString *imagePath = [filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg", photo.name]];
            [UIImagePNGRepresentation(photo.image)writeToFile:imagePath atomically:YES];
            [info setObject:imagePath forKey:@"ImagePath"];
            [info setObject:photo.name forKey:@"Name"];
            [info setObject:photo.tags forKey:@"Tags"];
            [info setObject:photo.date forKey:@"Date"];
            
            [savePhotos addObject:info];
        }
        [savePhotos writeToFile:plistPath atomically:YES];
    }

    读取图片:

    - (NSArray *)loadPhotosFromDisk {
        //从本地读取图片
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *plistPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"photo_info.plist"];
    
        NSArray *photosArr = [NSArray arrayWithContentsOfFile:plistPath];
        for (NSDictionary *dic in photosArr) {
            Photo *photo = [[Photo alloc] init];
            photo.image = [UIImage imageWithContentsOfFile:[dic valueForKey:@"ImagePath"]];
            photo.name = [dic valueForKey:@"Name"];
            photo.tags = [dic valueForKey:@"Tags"];
            photo.date = [dic valueForKey:@"Date"];
            [self.photos addObject:photo];
        }
        
        return self.photos;
    }
  • 相关阅读:
    在jsp页面如果运行时路径错误解决方法
    Maven实现ssm框架整合
    JS进阶(二)this指南——绑定了谁?
    防御性编程方法收集
    react将多个公共组件归成一类,方便调用
    初始化构建React+Ts项目时出现:Module build failed (from ./node_modules/css-loader/dist/cjs.js): CssSyntaxError
    Dva三种方式实现dispatch的Promise回调
    ES6多层解构
    ES6解构过程添加一个默认值和赋值一个新的值
    Antd-Pro2.0版本如何修改代理,让Mock变为真实服务器接口
  • 原文地址:https://www.cnblogs.com/liuliuliu/p/4561400.html
Copyright © 2011-2022 走看看