今天刚进入学习ios高阶课,第一节课讲的是数据处理之文件读写。
以下是自己整理的一些笔记
首先学了沙盒机制,沙盒是一种安全体系,它规定应用程序只能在为该应用程序创建的文件夹(沙盒)内访问文件,不可以去访问其他沙盒的内容(ios8已经部分开发访问);同时,所有的非代码文件都存储在这个地方,如声音、图片、属性列表(plist)、sqlite数据库和文本文件等等。
沙盒的特点:
1.每个应用程序的活动范围都限定在自己的沙盒内;
2.不能随意跨越自己的沙盒去访问别的应用的沙盒中的内容
3.应用程序向外请求或接收数据都要经过授权
沙盒目录下有3个文件夹Documents、Library(里面有Caches和Preferences目录)、tmp。
Documents是用来保存应用运行时生成的需要持久化的数据;
Library是存储程序的默认设置和其他状态信息;
Caches是存放缓存文件的,这个目录里的文件不会在程序退出时删除, 一般放体积较大,不是很重要的资源。
Preferences是保存应用的偏好设置,iOS的settings应用汇在这个目录中查找应用的设置信息。
**注意:不可以直接创建偏好设置文件,应该用NSUserDefaults类来获取和设置应用的偏好。**
tmp是保存应用运行的时候所需要的临时数据,使用过后再将该目录中的文件删除。应用没有运行的时候,系统也可能清除该目录下的文件。iphone重启,会删除该目录下的文件。
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSLog(@"documentsPath___%@", documentsPath);
NSString *tmpPath = NSTemporaryDirectory();
NSLog(@"tmpPath____%@", tmpPath);
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSLog(@"cachesPath____%@", cachesPath);
NSString *path = [documentsPath stringByAppendingPathComponent:@"path"];
[fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
NSLog(@"path____%@", path);
NSString *testPath = [path stringByAppendingPathComponent:@"test.txt"];
UIImage *image = [UIImage imageNamed:@"13.jpg"];
NSData *data = UIImagePNGRepresentation(image);
[fileManager createFileAtPath:testPath contents:data attributes:nil];
NSLog(@"testPath____%@", testPath);
NSString *testDirPath = [tmpPath stringByAppendingPathComponent:@"testDirectory/test.txt"];
[fileManager createDirectoryAtPath:[testDirPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];
[fileManager copyItemAtPath:testPath toPath:testDirPath error:nil];
NSLog(@"testDirPath____%@", testDirPath);
NSString *documentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/path/test.txt"];
UIImage *image = [UIImage imageNamed:@"13.jpg"];
NSData *data = UIImagePNGRepresentation(image);
[fileManager createDirectoryAtPath:[documentsPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];
[data writeToFile:documentsPath atomically:YES];
NSLog(@"documentsPath___%@", documentsPath);
NSString *tmpPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"testDirectory/test.txt"];
[fileManager createDirectoryAtPath:[tmpPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];
[fileManager copyItemAtPath:documentsPath toPath:tmpPath error:nil];
NSLog(@"tmpPath___%@", tmpPath);
上面是一些练习,简单的获取沙盒的文件夹路径与创建文件、文件夹、文件的复制。