不需要多解释,直接上代码说明,代码中有相关注释
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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | // Home路径 NSString *homePath = NSHomeDirectory(); // Caches路径 NSArray *caches = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); NSString *cachesPath = [caches firstObject]; // Documents路径 NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsPath = [documents firstObject]; // Tmp路径 NSString *tmp = NSTemporaryDirectory(); // 数组读写操作 NSArray *array = @[@"a",@"b"]; // 1、设置文件路径 NSString *arrayPath = [documentsPath stringByAppendingPathComponent:@"array.plist"]; // 2、写入文件 [array writeToFile:arrayPath atomically:YES]; // 3、从文件获取数据 NSArray *getArray = [NSArray arrayWithContentsOfFile:arrayPath]; // 4、输出打印 NSLog(@"%@", getArray); // 字典读写操作 NSDictionary *dict = @{@"1":@"one", @"2":@"two"}; NSString *dictPath = [documentsPath stringByAppendingPathComponent:@"dict.plist"]; [dict writeToFile:dictPath atomically:YES]; NSDictionary *getDict = [NSDictionary dictionaryWithContentsOfFile:dictPath]; NSLog(@"%@", getDict); // 字符串读写操作 NSString *string = @"小龙虾论坛地址:www.yusian.com"; NSString *strPath = [documentsPath stringByAppendingPathComponent:@"string.txt"]; [string writeToFile:strPath atomically:YES encoding:NSUTF8StringEncoding error:nil]; NSString *getStr = [NSString stringWithContentsOfFile:strPath encoding:NSUTF8StringEncoding error:nil]; NSLog(@"%@", getStr); // 图片读写操作 UIImage *image = [UIImage imageNamed:@"001.jpg"]; // 图片一般存储在Caches目录 NSString *imagePath = [cachesPath stringByAppendingPathComponent:@"001.jpg"]; // 图片不直接存储,需压缩成Data格式 NSData *imageData = UIImageJPEGRepresentation(image, 0.1); // 写入本地沙盒 [imageData writeToFile:imagePath atomically:YES]; // 获取图片 UIImage *getImage = [UIImage imageWithContentsOfFile:imagePath]; |
相关链接:
Pingback: iOS开发中自定义对象的归档 | 小龙虾博客 (Crayfish)