在iOS开发中,删除Sandbox中Documents目录下的文件可能是个比较常用的操作,下面是我封装的部分代码:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *fileName = @"test";
NSString *filePath = [self getDirectoryOfDocumentFileWithName:fileName];
NSLog(@"%@", filePath);
if (filePath) {
[self removeFileAtPath:filePath];
}
}
- (NSString *)getDirectoryOfDocumentFolder {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); // 获取所有Document文件夹路径
NSString *documentsPath = paths[0]; // 搜索目标文件所在Document文件夹的路径,通常为第一个
if (!documentsPath) {
NSLog(@"Documents目录不存在");
}
return documentsPath;
}
- (NSString *)getDirectoryOfDocumentFileWithName:(NSString *)fileName {
NSString *documentsPath = [self getDirectoryOfDocumentFolder];
if (documentsPath) {
return [documentsPath stringByAppendingPathComponent:fileName]; // 获取用于存取的目标文件的完整路径
}
return nil;
}
- (BOOL)isFileExitsAtPath:(NSString *)filePath {
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:filePath isDirectory:NULL]) {
return YES;
}
return NO;
}
- (void)removeFileAtPath:(NSString *)filePath {
NSError *error = nil;
if ([self isFileExitsAtPath:filePath]) {
[[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
if (error) {
NSLog(@"移除文件失败,错误信息:%@", error);
}
else {
NSLog(@"成功移除文件");
}
}
else {
NSLog(@"文件不存在");
}
}
在viewDidLoad方法中,fileName给出了Documents文件夹中的文件名,然后获取其完整路径,并通过remove方法来移除。
在Documents下新建一个test文件夹,运行后控制台输出:
2014-03-15 13:02:54.527 RemoveDocument[849:70b] /Users/apple/Library/Application Support/iPhone Simulator/7.0.3/Applications/AA0DC0B6-EED1-4F2F-B470-326B7A5CB656/Documents/test
2014-03-15 13:02:54.529 RemoveDocument[849:70b] 成功移除文件
非常成功。
但是,假如fileName为空白,例如:
// NSString *fileName = @"test";
NSString *fileName = @"";
运行看看,控制台输出如下:
2014-03-15 13:01:14.381 RemoveDocument[816:70b] /Users/apple/Library/Application Support/iPhone Simulator/7.0.3/Applications/AA0DC0B6-EED1-4F2F-B470-326B7A5CB656/Documents
2014-03-15 13:01:14.383 RemoveDocument[816:70b] 成功移除文件
打开模拟器目录:
可以看见整个Documents文件夹都被删除了。原因是如果为stringByAppendingPathComponent:方法传递的参数是@"",那么返回的就是当前路径,即Documents文件夹的路径。
这种行为非常非常的危险,要特别小心。
比较保险的方法是先做一个判断:
- (void)viewDidLoad
{
[super viewDidLoad];
// NSString *fileName = @"test";
NSString *fileName = @"";
NSString *filePath = [self getDirectoryOfDocumentFileWithName:fileName];
NSLog(@"%@", filePath);
if (filePath) {
[self removeFileAtPath:filePath];
}
}
- (NSString *)getDirectoryOfDocumentFileWithName:(NSString *)fileName {
if ([fileName isEqualToString:@""]) {
return nil;
}
NSString *documentsPath = [self getDirectoryOfDocumentFolder];
if (documentsPath) {
return [documentsPath stringByAppendingPathComponent:fileName]; // 获取用于存取的目标文件的完整路径
}
return nil;
}
当然也可以把判断放在getDirectoryOfDocumentFileWithName:方法之外,这个视需求而定。