年年有"余"

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 1725|回复: 0

iOS开发中基本文件读写操作示例

[复制链接]
  • TA的每日心情
    奋斗
    2022-12-13 21:26
  • 签到天数: 371 天

    [LV.9]以坛为家II

    发表于 2014-11-5 21:01:57 | 显示全部楼层 |阅读模式
    不需要多解释,直接上代码说明,代码中有相关注释
    1.     // Home路径
    2.     NSString *homePath = NSHomeDirectory();
    3.    
    4.     // Caches路径
    5.     NSArray *caches = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    6.     NSString *cachesPath = [caches firstObject];
    7.    
    8.     // Documents路径
    9.     NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    10.     NSString *documentsPath = [documents firstObject];
    11.    
    12.     // Tmp路径
    13.     NSString *tmp = NSTemporaryDirectory();
    14.    
    15.    
    16.     // 数组读写操作
    17.     NSArray *array = @[@"a",@"b"];
    18.     // 1、设置文件路径
    19.     NSString *arrayPath = [documentsPath stringByAppendingPathComponent:@"array.plist"];
    20.     // 2、写入文件
    21.     [array writeToFile:arrayPath atomically:YES];
    22.     // 3、从文件获取数据
    23.     NSArray *getArray = [NSArray arrayWithContentsOfFile:arrayPath];
    24.     // 4、输出打印
    25.     NSLog(@"%@", getArray);
    26.     // 字典读写操作
    27.     NSDictionary *dict = @{@"1":@"one", @"2":@"two"};
    28.     NSString *dictPath = [documentsPath stringByAppendingPathComponent:@"dict.plist"];
    29.     [dict writeToFile:dictPath atomically:YES];
    30.     NSDictionary *getDict = [NSDictionary dictionaryWithContentsOfFile:dictPath];
    31.     NSLog(@"%@", getDict);
    32.    
    33.     // 字符串读写操作
    34.     NSString *string = @"小龙虾论坛地址:www.yusian.com";
    35.     NSString *strPath = [documentsPath stringByAppendingPathComponent:@"string.txt"];
    36.     [string writeToFile:strPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    37.     NSString *getStr = [NSString stringWithContentsOfFile:strPath encoding:NSUTF8StringEncoding error:nil];
    38.     NSLog(@"%@", getStr);
    39.     // 图片读写操作
    40.     UIImage *image = [UIImage imageNamed:@"001.jpg"];
    41.     // 图片一般存储在Caches目录
    42.     NSString *imagePath = [cachesPath stringByAppendingPathComponent:@"001.jpg"];
    43.     // 图片不直接存储,需压缩成Data格式
    44.     NSData *imageData = UIImageJPEGRepresentation(image, 0.1);
    45.     // 写入本地沙盒
    46.     [imageData writeToFile:imagePath atomically:YES];
    47.     // 获取图片
    48.     UIImage *getImage = [UIImage imageWithContentsOfFile:imagePath];
    复制代码
    常用路径及路径获取参考链接:http://www.yusian.com/bbs/thread-7978-1-1.html
    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    手机版|小黑屋|Archiver|iOS开发笔记 ( 湘ICP备14010846号 )

    GMT+8, 2024-5-2 23:44 , Processed in 0.048098 second(s), 20 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表