iOS怎么获取并移除沙盒中Documents文件夹下的所有文件

将所有文件存入数组

NSString *string = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *tempFileList = [[NSArray alloc] initWithArray:[fileManager contentsOfDirectoryAtPath:string error:nil]];



移除所有文件

NSString *DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:DocumentsPath];
for (NSString *fileName in enumerator) {
    [[NSFileManager defaultManager] removeItemAtPath:[DocumentsPath stringByAppendingPathComponent:fileName] error:nil];
}



移除所有png文件

NSString *extension = @"png";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil];
NSEnumerator *enumerator = [contents objectEnumerator];
NSString *filename;
while ((filename = [enumerator nextObject])) {
    if ([[filename pathExtension] isEqualToString:extension]) {
        [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:nil];
    }
}


你可能感兴趣的:(ios开发)