Dawninest

Objective-C | 数据的外部储存和读取

设备存储路径

每一个App,iOS系统将会预设3个文件夹体感存储功能

  • documents路径
1
NSString *documentString = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
  • library路径
1
NSString *libraryString = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)lastObject];
  • tmp路径 - tmp作为临时存储,不向其中存储需要持久保留的数据
1
NSString *tmpString = NSTemporaryDirectory();

把工程中的图片写入沙盒

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
1.保存图片的路径
NSString *documentString = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
NSString *saveImagePath = [documentString stringByAppendingString:@“/图片名”];
2.获取图片
NSString *path = [[NSBundle mainBundle]pathForResource:@“图片名” ofType:@“png”];
UIImage *image = [UIImage imageWithContentsOfFile:path];
3.把图片转换为data
NSData *imageData = UIImagePNGRepresentation(image);
4.写入沙盒
NSFileManager *manager = [NSFileManager defaultManager];//单例
if (![manager fileExistsAtPath:saveImagePath]) {
[manager createFileAtPath:saveImagePath contents:imageData attributes:nil];
}

读取指定文件下的图片
[UIImage imageWithContentsOfFile:saveImagePath];

存储自定义对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
例子:存储联系人信息数组

存储
1.获取联系人对象
Contact *acontact = [[Contact alloc]initWithDictionary:[self userDic]];
2.获取保存文件路径
NSString *plistPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
plistPath = [plistPath stringByAppendingString:@"/data.plist"];
3.初始化写入沙盒的数组
NSMutableArray *dataList = [NSMutableArray array];
4.归档(自动调用归档方法)
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:acontact];
5.把归档所得数据添加的数组
[dataList addObject:data];
6.将数组写入沙盒
BOOL success = [dataList writeToFile:plistPath atomically:YES];
NSLog(@"是否保存成功:%d",success);

读取
1.获取保存文件的路径
NSString *plistPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
plistPath = [plistPath stringByAppendingString:@"/data.plist"];
2.读取沙盒文件
NSArray *results = [NSArray arrayWithContentsOfFile:plistPath];
3.解档
NSData *data = results[0];//取出data
Contact *acontact = [NSKeyedUnarchiver unarchiveObjectWithData:data];

删除
1.获取保存文件的路径
NSString *plistPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
plistPath = [plistPath stringByAppendingString:@"/data.plist"];
2.清除
NSFileManager *manager = [NSFileManager defaultManager];
BOOL success = [manager removeItemAtPath:plistPath error:nil];
NSLog(@"是否清除成功:%d",success);

NSUserDefaults 存沙盒

1
2
3
4
5

[[NSUserDefaults standardUserDefaults] setObject:@[@"1"] forKey:@"mydata"];
[[NSUserDefaults standardUserDefaults] synchronize];//同步至沙盒

NSArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:@"mydata"];