Get directory contents in date modified order

后端 未结 5 2140
盖世英雄少女心
盖世英雄少女心 2020-12-04 14:19

Is there an method to get the contents of a folder in a particular order? I\'d like an array of file attribute dictionaries (or just file names) ordered by date modified.

5条回答
  •  情深已故
    2020-12-04 15:14

    Code does not work in iPhone SDK, full of compilation error. Please find updated code `

    NSInteger lastModifiedSort(id path1, id path2, void* context)
    {
        int comp = [[path1 objectForKey:@"lastModDate"] compare:
         [path2 objectForKey:@"lastModDate"]];
        return comp;
    }
    
    -(NSArray *)filesByModDate:(NSString*) path{
    
        NSError* error = nil;
    
        NSArray* filesArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path
                                                                             error:&error];
        if(error == nil)
        {
            NSMutableArray* filesAndProperties = [NSMutableArray arrayWithCapacity:[filesArray count]];
    
            for(NSString* imgName in filesArray)
            {
    
                NSString *imgPath = [NSString stringWithFormat:@"%@/%@",path,imgName];
                NSDictionary* properties = [[NSFileManager defaultManager]
                                            attributesOfItemAtPath:imgPath
                                            error:&error];
    
                NSDate* modDate = [properties objectForKey:NSFileModificationDate];
    
                if(error == nil)
                {
                    [filesAndProperties addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                                                   imgName, @"path",
                                                   modDate, @"lastModDate",
                                                   nil]];                     
                }else{
                    NSLog(@"%@",[error description]);
                }
            }
            NSArray* sortedFiles = [filesAndProperties sortedArrayUsingFunction:&lastModifiedSort context:nil];
    
            NSLog(@"sortedFiles: %@", sortedFiles);      
            return sortedFiles;
        }
        else
        {
            NSLog(@"Encountered error while accessing contents of %@: %@", path, error);
        }
    
        return filesArray;
    }
    

    `

提交回复
热议问题