iOS数据存储

简单数据的存储

1. 获取沙盒的位置

NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

也可以使用

NSString *homePath = NSHomeDirectory();
    NSString *documentPath2 = [homePath stringByAppendingPathComponent:@"Documents"];

2. 简单数据的存储

2.1 NSString
(1)创建txt文件

NSString *str = @"ADC";
    NSString *strFilePath = [documentPath stringByAppendingPathComponent:@"str.txt"];

(2)写入数据

[str writeToFile:strFilePath atomically:YES];

(3)读取数据

NSString *readStr = [[NSString alloc] initWithContentsOfFile:strFilePath encoding:NSUTF8StringEncoding error:nil];

2.2 NSArray

//先创建一个存储array对象的txt文件路径
NSString *arrPath = [documentPath stringByAppendingPathComponent:@"array.txt"];
//使用字面量创建Array
    NSArray *nameArr = @[];
//将数据写入txt文件路径
    [nameArr writeToFile:arrPath atomically:YES];
//从路径读取出数据
    NSArray *arr = [NSArray arrayWithContentsOfFile:arrPath];

2.3 字典

//字典的处理步骤同NSArray  
NSString *dictPath = [documentPath stringByAppendingPathComponent:@"dict.txt"];
    
    NSDictionary *dict = @{};
    [dict writeToFile:dictPath atomically:YES];
    
    NSDictionary *readDict = [NSDictionary dictionaryWithContentsOfFile:dictPath];

2.4 NSData

NSString *imgPath = [documentPath stringByAppendingPathComponent:@"img.txt"];
    UIImage *image = [UIImage imageNamed:@"address"];
//将图片转换成NSData类型
    NSData *imgData = UIImagePNGRepresentation(image);
    
    [imgData writeToFile:imgPath atomically:YES];
    //读取图片
    UIImage *img = [UIImage imageWithContentsOfFile:imgPath];

2.5 从资源包读取图片

//获取绝对路径
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"address" ofType:@"png"];
//通过路径加载图片
    UIImage *image1 = [UIImage imageWithContentsOfFile:imagePath];
    
    imageView.image = image1;
    
    [self.view addSubview:imageView];
    
    UIView *view = [[NSBundle mainBundle] loadNibNamed:@"a" owner:self options:nil][0];

数据,文件操作

  1. 声明文件的路径
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  1. 创建txt文件及其路径
NSString *filePath = [documentPath stringByAppendingPathComponent:@"file.txt"];
  1. 创建FileManager,并初始化文件
NSFileManager *fileManager = [NSFileManager defaultManager];
    
    [fileManager createFileAtPath:filePath contents:strData attributes:nil];
  1. 读取数据
NSData *readStrData = [fileManager contentsAtPath:filePath];
    NSString *str1 = [[NSString alloc] initWithData:readStrData encoding:NSUTF8StringEncoding];
  1. 移动文件
    5.1 创建目标文件的路径
NSString *moveFilePath = [topath stringByAppendingPathComponent:@"file.txt"];

5.2 移动文件

    [fileManager moveItemAtPath:filePath toPath:moveFilePath error:nil];
  1. 复制文件
NSString *copyPath = [documentPath stringByAppendingPathComponent:@"备份/copy.txt"];
    
    [fileManager createDirectoryAtPath:[copyPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];
    
    [fileManager copyItemAtPath:moveFilePath toPath:copyPath error:nil];
  1. 获取文件信息(文件大小)
NSDictionary *dic = [fileManager attributesOfItemAtPath:filePath error:nil];
    
    NSInteger fileLength = [dic[NSFileSize] integerValue];
  1. 判断文件是否存在
[fileManager fileExistsAtPath:filePath]

使用NSFileHandle操作文件

//先通过fileManager创建文件并在里面写入内容
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSString *documentPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    
    NSString *filePath = [documentPath stringByAppendingPathComponent:@"file.txt"];
    
    [fileManager createFileAtPath:filePath contents:[@"abc" dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];

修改内容

NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
    //查找到文件最末端
    [fileHandle seekToEndOfFile];
    [fileHandle writeData:[@"123" dataUsingEncoding:NSUTF8StringEncoding]];
    
    [fileHandle closeFile];

读取文件

NSFileHandle *readFileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];
    //读取长度
    NSUInteger length = [[readFileHandle availableData] length];
    //设置偏移位置
    [readFileHandle seekToFileOffset:length/2];
    //从偏移位置开始读取到文件末尾
    NSData *readData = [readFileHandle readDataToEndOfFile];
    
    NSString *readStr = [[NSString alloc] initWithData:readData encoding:NSUTF8StringEncoding];

复制文件

NSString *copypath = [documentPath stringByAppendingPathComponent:@"copy.txt"];
    [fileManager createFileAtPath:copypath contents:nil attributes:nil];

    //打开文件准备写入
    NSFileHandle *copyHandle = [NSFileHandle fileHandleForWritingAtPath:copypath];
    //writeData会直接覆盖原来的
    [copyHandle writeData:readData];
    
    [copyHandle closeFile];

文件的归档与反归档

要进行归档, 必须先让类继承<NSCoding>并实现两个方法

//反序列化
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    if (self) {
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.age = [aDecoder decodeIntegerForKey:@"age"];
    }
    return self;
}
//序列化
- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeInteger:self.age forKey:@"age"];
}

归档过程:Person对象-->NSData-->writeFile

NSMutableData *mulData = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:mulData];
    [archiver encodeObject:person forKey:@"Person"];
    [archiver finishEncoding];

写入文件

NSString *personDataPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/person.txt"];
   
    [mulData writeToFile:personDataPath atomically:YES];

反归档过程: 从文件里面读取-->NSData-->Person对象

NSData *personData = [NSData dataWithContentsOfFile:personDataPath];
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:personData];
    Person *person1 = [unarchiver decodeObjectForKey:@"Person"];
    NSLog(@"perosn1 = %@", person1);

另外,还有一个系统单利类可以进行数据存储

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:@"123" forKey:@"userName"];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 学习了数据存储的NSUserDefaults,归档和解档,对于项目开发中如果要存储一些文件,比如图片,音频,...
    今天又要上班吗阅读 891评论 0 1
  • 27、ViewController的didReceiveMemoryWarning是在什么时候调用的?默认的操作是...
    烟雨平生花飞舞阅读 647评论 0 1
  • 一、iOS中的沙盒机制 iOS应用程序只能对自己创建的文件系统读取文件,这个独立、封闭、安全的空间,叫做沙盒。它一...
    1d5cb7cff98d阅读 1,798评论 0 0
  • iOS开发-文件管理(一) 一、iOS中的沙盒机制 iOS应用程序只能对自己创建的文件系统读取文件,这个独立、封闭...
    MacShare阅读 1,821评论 0 6
  • 还记得在《高效能人士的七个习惯》培训课上使命宣言那个环节Gus的开场,娓娓道来讲述着他的过往。 原来他的父母辈一样...
    Rafen阅读 1,070评论 9 8