0

我想删除给定文件夹中的所有文件夹,但最近的 10 个文件夹除外。

文件夹的年龄是其最年轻元素的年龄。

4

1 回答 1

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
于 2013-11-07T14:37:46.633 回答