我想删除指定文件夹中的所有文件夹,不包括最近的10个文件夹。
文件夹的年龄是其最年轻元素的年龄。
答案 0 :(得分:0)
//
// NSFileManager+KeepOnlyLastElements.m
//
#import "NSFileManager+KeepOnlyLastElements.h"
@implementation NSFileManager (KeepOnlyLastElements)
- (BOOL)keepOnlyLastElements:(NSUInteger)numberOfKeptElements
ofFolderWithURL:(NSURL *)URLPathFolder ;
{
BOOL isDirectory = NO ;
[self fileExistsAtPath:URLPathFolder.path
isDirectory:&isDirectory] ;
if (isDirectory)
{
NSArray * contentFolder = [self contentsOrderedByDateOfDirectoryAtPath:URLPathFolder] ;
NSUInteger length = [contentFolder count] ;
__block BOOL result = YES ;
__block NSError * error ;
[contentFolder enumerateObjectsUsingBlock:^(NSURL * currentURL, NSUInteger idx, BOOL *stop)
{
if (length - idx > numberOfKeptElements)
{
if ([self removeItemAtURL:currentURL
error:&error] == NO)
{
*stop = YES ;
result = NO ;
};
}
}];
if (!result)
{
NSLog(@"Error ! %@", error) ;
}
return result ;
}
else
{
NSLog(@"No foldet at URL %@", URLPathFolder) ;
return NO ;
}
}
static NSInteger contentsOfDirSort(NSURL *leftURL, NSURL *rightURL, void *ptr)
{
(void)ptr;
NSDate * dateLeft ;
dateLeft = [[[NSFileManager defaultManager] attributesOfItemAtPath:leftURL.path
error:NULL] valueForKey:NSFileModificationDate];
NSDate * dateRight ;
dateRight = [[[NSFileManager defaultManager] attributesOfItemAtPath:rightURL.path
error:NULL] valueForKey:NSFileModificationDate];
return [dateLeft compare:dateRight];
}
- (NSArray *)contentsOrderedByDateOfDirectoryAtPath:(NSURL *)URLOfFolder ;
{
NSArray *files = [self contentsOfDirectoryAtPath:URLOfFolder.path
error:NULL] ;
return [files sortedArrayUsingFunction:contentsOfDirSort
context:nil] ;
}
@end