YIem`s Blog -心比天高命比纸薄-链接找不到的请在站内搜索内容!

iOS-初级数据持久化_简单对象的读写(NSString/NSArray/NSDictionary/NSData)写入本地磁盘






//
// ViewController.m
// 初级数据持久化_简单对象的读写
//
// Created by YIem on 16/3/2.
// Copyright © 2016年 YIem. All rights reserved.
//

import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

pragma - NSString ()


// 构造字符串文件的存储路径
// 在路径上拼接文件名
NSString *filePath = [fileStr stringByAppendingPathComponent:@"str.txt"];
NSString *str = @"YIem";
// 将内容写入文件内 (字符串的写入)
// 参数1: 文件路径
// 参数2: 是否原子保护
// 参数3: 编码
// 参数4: 错误信息(反馈)
[str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
// 获取本地文件内容(字符串的读取)
NSString *backStr = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"读出内容为: %@", backStr);

pragma - NSArray ()


// 构造数组文件的存储路径
NSString *ArrayPath = [fileStr stringByAppendingPathComponent:@"/array.plist"];
// 构建数组对象
NSArray *arr = @[@"YI", @"YIem", @"卞一", @"卞", @"一"];
// 将内容写入文件
// 参数1: 文件路径
// 参数2: 是否原子保护
[arr writeToFile:ArrayPath atomically:YES];
// 从文件中读取数组对象
NSArray *resultArray = [NSArray arrayWithContentsOfFile:ArrayPath];
NSLog(@"数组对象为: %@", resultArray);

pragma - NSDictionary ()


// 构造字典文件的存储路径
NSString *dicPath = [fileStr stringByAppendingPathComponent:@"/dic.plist"];
// 构建字典对象
NSDictionary *dic = @{@"name":@"YIem", @"sex":@"男", @"age":@"21"};
// 将内容写入文件
// 参数1: 文件路径
// 参数2: 是否原子保护
[dic writeToFile:dicPath atomically:YES];
// 从文件中读取字典对象
NSDictionary *resultDic = [NSDictionary dictionaryWithContentsOfFile:dicPath];
NSLog(@"字典对象为: %@", resultDic);

pragma - NSData ()


// NSData 对象写入文件
UIImage *image = [UIImage imageNamed:@"1.png"];
NSData *data = UIImagePNGRepresentation(image);
// 构建二进制文件的存储路径
NSString *dataPath = [fileStr stringByAppendingString:@"/data"];
// 将内容写入文件
// 参数1: 文件路径
// 参数2: 是否原子保护
[data writeToFile:dataPath atomically:YES];
// * 注 : 二进制对象可能存储的是 图像/字符串 等等

// 从文件中读取NSData
NSData *resultData = [NSData dataWithContentsOfFile:dataPath];
UIImage *resultImage = [UIImage imageWithData:resultData];
NSLog(@"NSData: %@", resultImage);

}

@end

当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »