UIday1801:沙盒三个文件的路径的获取、简单与复杂对象的读写、NSUserDefaults、NSFileManager

本文主要是介绍UIday1801:沙盒三个文件的路径的获取、简单与复杂对象的读写、NSUserDefaults、NSFileManager,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

初级数据持久化(沙盒三个文件的路径的获取、简单与复杂对象的读写、NSUserDefaults、NSFileManager  )

NSDocumentDirectory 是指程序中对应的Documents路径,而NSDocumentionDirectory对应于程序中的Library/Documentation路径,这个路径是没有读写权限的,所以看不到文件生成。

IOS开发是在沙盒中开发的,对一些部分的文件的读写进行了限制,只能在几个目录下读写文件:
 (1)Documents:应用中用户数据可以放在这里,iTunes备份和恢复的时候会包括此目录
 (2)tmp:存放临时文件,iTunes不会备份和恢复此目录,此目录下文件可能会在应用退出后删除
 (3)Library/Caches:存放缓存文件,iTunes不会备份此目录,此目录下文件不会在应用退出删除
 对于文件操作,NSSearchPathForDirectoriesInDomains是核心函数。


ViewController.m

#import "ViewController.h"
#import "Person.h"@interface ViewController ()@property(nonatomic,strong)UIImageView * imV;@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];// Do any additional setup after loading the view, typically from a nib.// 沙盒 就是一个文件夹// *********获取沙盒路径************
/*// 获取用户名NSString * s = NSUserName();// 获取主路径NSString * rootPath = NSHomeDirectoryForUser(s);NSLog(@"%@",rootPath);*/// ************获取沙盒三个文件夹的路径***********/*// otherNSString * rootPath1 = NSHomeDirectory();NSLog(@"rootPath1 = %@",rootPath1);// 获取doucments路径// 作用 数据运行程序后产生,主要存储数据库等不常改变的数据文件。存在这里的文件会被备份。(下载的文件不能放在这里,如果放在这上传APPStore的时候会被拒掉)NSString * documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];NSLog(@"documentsPath = %@",documentsPath);// 获取Caches路径// 作用存放缓存文件,例如:音频、视频、图片(不会被自动备份)NSString * cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];NSLog(@"cachesPath = %@",cachesPath);// 获取tmp路径// 作用:存放临时文件,程序下次启动不需要,退出清空。NSString * tmpPath = NSTemporaryDirectory();NSLog(@"tmpPath = %@",tmpPath);*///***********简单文件的写入*****************
/*//准备路径NSString * documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];NSLog(@"%@",documentsPath);//----------------NSString的写和读---------------//NSString  NSArray  NSDictionary  NSDataNSString * str1 = @"hello world";NSString * filePath = [documentsPath stringByAppendingString:@"/hello.txt"];//写入
//    [str1 writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];//读出NSString *s1 = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];NSLog(@"s1 = %@" ,s1);//------------- NSArray 的写和读 --------------//stringByAppendingPathComponent: 路径不需要写斜线,不需要写后缀NSString * filePath2 = [documentsPath stringByAppendingPathComponent:@"array"];NSArray *array1 = @[@"1",@"2",@"3"];//写入
//    [array1 writeToFile:filePath2 atomically:YES];//读NSArray * array2 = [NSArray arrayWithContentsOfFile:filePath2];//    NSLog(@"array2 = %@",array2);//------------- NSDictionary 的写和读------------NSString * filePath3 = [documentsPath stringByAppendingPathComponent:@"Dictionary"];//写入NSDictionary * dict = @{@"山西":@"太原",@"河北":@"石家庄"};[dict writeToFile:filePath3 atomically:YES];//读NSDictionary * dict2 = [NSDictionary dictionaryWithContentsOfFile:filePath3];NSLog(@"dict2  %@",dict2);//遍历字典for (id obj in dict2) {NSLog(@"dict2 %@ = %@",obj,[dict2 valueForKey:obj]);}*///*************** 复杂对象写入1 *****************
/*//创建对象Person * p1 = [[Person alloc]init];p1.name = @"贝爷";p1.age = 20;//准备NSMutableData 存数据NSMutableData * data = [NSMutableData data];创建归档工具NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];//开始归档[archiver encodeObject:p1 forKey:@"p1"];//完成归档[archiver finishEncoding];//准备路径NSString * documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];NSString * filePath4 = [documentsPath stringByAppendingPathComponent:@"贝爷.m"];NSLog(@"%@",documentsPath);//data写入
//    [data writeToFile:filePath4 atomically:YES];//读NSData * data1 = [NSData dataWithContentsOfFile:filePath4];NSLog(@"data1 = %@",data1);//反归档NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data1];//转换成对象Person * p2 = [unarchiver decodeObjectForKey:@"p1"];//反归档完成[unarchiver finishDecoding];NSLog(@"%@ == %ld",p2.name,p2.age);*///*************** 复杂对象写入2 *****************
/*//准备路径NSString * documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];//拼接路径NSString * filePath5 = [documentsPath stringByAppendingPathComponent:@"person.mp4"];//创建person对象Person *p3 = [[Person alloc]init];p3.name = @"六娃";p3.age = 18;//存
//    [NSKeyedArchiver archiveRootObject:p3 toFile:filePath5];//取 (这种归档方式,只能针对一个对象)Person * p4 = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath5];NSLog(@"%@ == %ld",p4.name,p4.age);*///************* NSUserDefaults 通常用来写引导页 ********
/*// 创建对象NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];// 存[ud setObject:@"yan3" forKey:@"lanou"];// 同步数据[ud synchronize];// 取NSLog(@"%@",[ud objectForKey:@"lanou"]);*///************** 导航页测试 ****************
/*// 创建对象// NSUserDefaults 存一些简单的数据NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];NSString *s = [ud objectForKey:@"first"];if (s == nil) {self.imV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"000.png"]];self.imV.frame = self.view.bounds;[self.view addSubview:_imV];[ud setObject:@"NO" forKey:@"first"];}*///*********** NSFileManager 文件管理对象 ************//路径NSString * cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];NSLog(@"%@",cachesPath);//创建文件管理对象NSFileManager * fm = [NSFileManager defaultManager];//创建文件夹[fm createDirectoryAtPath:[cachesPath stringByAppendingPathComponent:@"00/test"] withIntermediateDirectories:YES attributes:nil error:nil];//更改文件名[fm moveItemAtPath:[cachesPath stringByAppendingPathComponent:@"00/test"] toPath:[cachesPath stringByAppendingPathComponent:@"Demo"] error:nil];//移动文件位置[fm moveItemAtPath:[cachesPath stringByAppendingPathComponent:@"00/test"] toPath:[cachesPath stringByAppendingPathComponent:@"Demo/test"] error:nil];//删除文件[fm removeItemAtPath:[cachesPath stringByAppendingPathComponent:@"Demo/test"] error:nil];//判断一个文件是否存在BOOL i = [fm fileExistsAtPath:@"Demo"];NSLog(@"%d",i);    }- (void)didReceiveMemoryWarning {[super didReceiveMemoryWarning];// Dispose of any resources that can be recreated.
}@end

Person.h

#import <Foundation/Foundation.h>//一个类是否可以被归档反归档,要看是否遵循NSCoding协议。@interface Person : NSObject<NSCoding>@property(nonatomic,copy)NSString * name;@property(nonatomic,assign)NSInteger age;@end

Person.m

#import "Person.h"@implementation Person// 编码
- (void)encodeWithCoder:(NSCoder *)aCoder{[aCoder encodeObject:self.name forKey:@"p_name"];[aCoder encodeInteger:self.age forKey:@"p_age"];
}// 反编码
- (id)initWithCoder:(NSCoder *)aDecoder{if (self = [super init]) {self.name = [aDecoder decodeObjectForKey:@"p_name"];self.age = [aDecoder decodeIntegerForKey:@"p_age"];}return self;}@end


这篇关于UIday1801:沙盒三个文件的路径的获取、简单与复杂对象的读写、NSUserDefaults、NSFileManager的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/884626

相关文章

ShardingProxy读写分离之原理、配置与实践过程

《ShardingProxy读写分离之原理、配置与实践过程》ShardingProxy是ApacheShardingSphere的数据库中间件,通过三层架构实现读写分离,解决高并发场景下数据库性能瓶... 目录一、ShardingProxy技术定位与读写分离核心价值1.1 技术定位1.2 读写分离核心价值二

SpringBoot 获取请求参数的常用注解及用法

《SpringBoot获取请求参数的常用注解及用法》SpringBoot通过@RequestParam、@PathVariable等注解支持从HTTP请求中获取参数,涵盖查询、路径、请求体、头、C... 目录SpringBoot 提供了多种注解来方便地从 HTTP 请求中获取参数以下是主要的注解及其用法:1

SpringBoot路径映射配置的实现步骤

《SpringBoot路径映射配置的实现步骤》本文介绍了如何在SpringBoot项目中配置路径映射,使得除static目录外的资源可被访问,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一... 目录SpringBoot路径映射补:springboot 配置虚拟路径映射 @RequestMapp

Python 基于http.server模块实现简单http服务的代码举例

《Python基于http.server模块实现简单http服务的代码举例》Pythonhttp.server模块通过继承BaseHTTPRequestHandler处理HTTP请求,使用Threa... 目录测试环境代码实现相关介绍模块简介类及相关函数简介参考链接测试环境win11专业版python

Java实现复杂查询优化的7个技巧小结

《Java实现复杂查询优化的7个技巧小结》在Java项目中,复杂查询是开发者面临的“硬骨头”,本文将通过7个实战技巧,结合代码示例和性能对比,手把手教你如何让复杂查询变得优雅,大家可以根据需求进行选择... 目录一、复杂查询的痛点:为何你的代码“又臭又长”1.1冗余变量与中间状态1.2重复查询与性能陷阱1.

使用Java读取本地文件并转换为MultipartFile对象的方法

《使用Java读取本地文件并转换为MultipartFile对象的方法》在许多JavaWeb应用中,我们经常会遇到将本地文件上传至服务器或其他系统的需求,在这种场景下,MultipartFile对象非... 目录1. 基本需求2. 自定义 MultipartFile 类3. 实现代码4. 代码解析5. 自定

python连接sqlite3简单用法完整例子

《python连接sqlite3简单用法完整例子》SQLite3是一个内置的Python模块,可以通过Python的标准库轻松地使用,无需进行额外安装和配置,:本文主要介绍python连接sqli... 目录1. 连接到数据库2. 创建游标对象3. 创建表4. 插入数据5. 查询数据6. 更新数据7. 删除

Jenkins的安装与简单配置过程

《Jenkins的安装与简单配置过程》本文简述Jenkins在CentOS7.3上安装流程,包括Java环境配置、RPM包安装、修改JENKINS_HOME路径及权限、启动服务、插件安装与系统管理设置... 目录www.chinasem.cnJenkins安装访问并配置JenkinsJenkins配置邮件通知

javaSE类和对象进阶用法举例详解

《javaSE类和对象进阶用法举例详解》JavaSE的面向对象编程是软件开发中的基石,它通过类和对象的概念,实现了代码的模块化、可复用性和灵活性,:本文主要介绍javaSE类和对象进阶用法的相关资... 目录前言一、封装1.访问限定符2.包2.1包的概念2.2导入包2.3自定义包2.4常见的包二、stati

MySQL中读写分离方案对比分析与选型建议

《MySQL中读写分离方案对比分析与选型建议》MySQL读写分离是提升数据库可用性和性能的常见手段,本文将围绕现实生产环境中常见的几种读写分离模式进行系统对比,希望对大家有所帮助... 目录一、问题背景介绍二、多种解决方案对比2.1 原生mysql主从复制2.2 Proxy层中间件:ProxySQL2.3