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

相关文章

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

MySQL 获取字符串长度及注意事项

《MySQL获取字符串长度及注意事项》本文通过实例代码给大家介绍MySQL获取字符串长度及注意事项,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录mysql 获取字符串长度详解 核心长度函数对比⚠️ 六大关键注意事项1. 字符编码决定字节长度2

python3如何找到字典的下标index、获取list中指定元素的位置索引

《python3如何找到字典的下标index、获取list中指定元素的位置索引》:本文主要介绍python3如何找到字典的下标index、获取list中指定元素的位置索引问题,具有很好的参考价值,... 目录enumerate()找到字典的下标 index获取list中指定元素的位置索引总结enumerat

MySQL主从复制与读写分离的用法解读

《MySQL主从复制与读写分离的用法解读》:本文主要介绍MySQL主从复制与读写分离的用法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、主从复制mysql主从复制原理实验案例二、读写分离实验案例安装并配置mycat 软件设置mycat读写分离验证mycat读

Redis分片集群、数据读写规则问题小结

《Redis分片集群、数据读写规则问题小结》本文介绍了Redis分片集群的原理,通过数据分片和哈希槽机制解决单机内存限制与写瓶颈问题,实现分布式存储和高并发处理,但存在通信开销大、维护复杂及对事务支持... 目录一、分片集群解android决的问题二、分片集群图解 分片集群特征如何解决的上述问题?(与哨兵模

SpringMVC高效获取JavaBean对象指南

《SpringMVC高效获取JavaBean对象指南》SpringMVC通过数据绑定自动将请求参数映射到JavaBean,支持表单、URL及JSON数据,需用@ModelAttribute、@Requ... 目录Spring MVC 获取 JavaBean 对象指南核心机制:数据绑定实现步骤1. 定义 Ja

Python打印对象所有属性和值的方法小结

《Python打印对象所有属性和值的方法小结》在Python开发过程中,调试代码时经常需要查看对象的当前状态,也就是对象的所有属性和对应的值,然而,Python并没有像PHP的print_r那样直接提... 目录python中打印对象所有属性和值的方法实现步骤1. 使用vars()和pprint()2. 使

C++中RAII资源获取即初始化

《C++中RAII资源获取即初始化》RAII通过构造/析构自动管理资源生命周期,确保安全释放,本文就来介绍一下C++中的RAII技术及其应用,具有一定的参考价值,感兴趣的可以了解一下... 目录一、核心原理与机制二、标准库中的RAII实现三、自定义RAII类设计原则四、常见应用场景1. 内存管理2. 文件操

SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志

《SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志》在SpringBoot项目中,使用logback-spring.xml配置屏蔽特定路径的日志有两种常用方式,文中的... 目录方案一:基础配置(直接关闭目标路径日志)方案二:结合 Spring Profile 按环境屏蔽关

SpringBoot服务获取Pod当前IP的两种方案

《SpringBoot服务获取Pod当前IP的两种方案》在Kubernetes集群中,SpringBoot服务获取Pod当前IP的方案主要有两种,通过环境变量注入或通过Java代码动态获取网络接口IP... 目录方案一:通过 Kubernetes Downward API 注入环境变量原理步骤方案二:通过