Question

I would like to remove all the folders in a given folder, excepted the 10 most recent ones.

The age of a folder is the age of its youngest element.

Was it helpful?

Solution

//
//  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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top