获取相关路径
- 沙盒路径
NSString *sandBoxPath = NSHomeDirectory();
- 沙盒中有三个文件夹Documents Library Tmp
- Documents路径
NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, NO)[0];
- Library路径
NSString *library = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)[0];
- Tmp路径
NSString *tmp = NSTemporaryDirectory();
存取数据
- 以一个字符串为例 数组字典方法基本相同
- 存入数据
NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
[user setObject:@"huahua" forKey:@"name"];
[user synchronize];
//2.自定义存储路径
//获取想要存储的目录
NSString *document = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
//在沙盒目标文件夹下创建文件
NSString *newPath = [document stringByAppendingString:@"/text.txt"];
//要存入的内容
NSString *string = @"花花的故事";
[string writeToFile:newPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
- 获取数据
//获取想要得到字符串的路径
NSString *document = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *newPath = [document stringByAppendingString:@"/text.txt"];
//从该路径获取字符串
NSString *string = [NSString stringWithContentsOfFile:newPath encoding:NSUTF8StringEncoding error:nil];```
- image转化为Data存取
//获取一张图片
UIImage *image = [UIImage imageNamed:@"image.png"];
//将图片转为为Data对象 注意有 png 和 jpg 两个方法 方法不同转化得到图片格式不同
NSData *data = UIImagePNGRepresentation(image);
//得到要存储的路径
NSString *path = [document stringByAppendingString:@"/imageData"];
//将data写入对应路径
[data writeToFile:path atomically:YES];
//获取该路径的data对象
NSData *imageData = [NSData dataWithContentsOfFile:path];
//将data对象转化为图片
UIImage *newImage = [UIImage imageWithData:imageData];```