以修改日期的顺序获取目录内容

nev*_*ing 34 iphone objective-c nsfilemanager

有没有一种方法来获取特定顺序的文件夹的内容?我想要一个按修改日期排序的文件属性字典数组(或只是文件名).

现在,我这样做:

  • 获取一个包含文件名的数组
  • 获取每个文件的属性
  • 将文件的路径和修改日期存储在字典中,并将日期作为键

接下来我必须按日期顺序输出字典,但我想知道是否有更简单的方法?如果没有,是否有一个代码片段可以为我做这个?

谢谢.

M-V*_*M-V 35

上面的nall代码指出了我正确的方向,但我认为上面发布的代码中存在一些错误.例如:

  1. 为什么filesAndProperties分配使用NMutableDictonary而不是NSMutableArray

  2. 
    NSDictionary* properties = [[NSFileManager defaultManager]
                                            attributesOfItemAtPath:NSFileModificationDate
                                            error:&error];
    
    
    Run Code Online (Sandbox Code Playgroud) 上面的代码传递了错误的参数attributesOfItemAtPath- 它应该是attributesOfItemAtPath:path

  3. 你正在排序files数组,但你应该排序filesAndProperties.


我已经实现了相同的,更正和使用块,并在下面发布:


    NSArray *searchPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsPath = [searchPaths objectAtIndex: 0]; 

    NSError* error = nil;
    NSArray* filesArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:&error];
    if(error != nil) {
        NSLog(@"Error in reading files: %@", [error localizedDescription]);
        return;
    }

    // sort by creation date
    NSMutableArray* filesAndProperties = [NSMutableArray arrayWithCapacity:[filesArray count]];
    for(NSString* file in filesArray) {
        NSString* filePath = [iMgr.documentsPath stringByAppendingPathComponent:file];
        NSDictionary* properties = [[NSFileManager defaultManager]
                                    attributesOfItemAtPath:filePath
                                    error:&error];
        NSDate* modDate = [properties objectForKey:NSFileModificationDate];

        if(error == nil)
        {
            [filesAndProperties addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                                           file, @"path",
                                           modDate, @"lastModDate",
                                           nil]];                 
        }
    }

        // sort using a block
        // order inverted as we want latest date first
    NSArray* sortedFiles = [filesAndProperties sortedArrayUsingComparator:
                            ^(id path1, id path2)
                            {                               
                                // compare 
                                NSComparisonResult comp = [[path1 objectForKey:@"lastModDate"] compare:
                                                           [path2 objectForKey:@"lastModDate"]];
                                // invert ordering
                                if (comp == NSOrderedDescending) {
                                    comp = NSOrderedAscending;
                                }
                                else if(comp == NSOrderedAscending){
                                    comp = NSOrderedDescending;
                                }
                                return comp;                                
                            }];

Run Code Online (Sandbox Code Playgroud)

  • 要反转排序,你可以使用`return [[path2 objectForKey:@"lastModDate"]比较:[path1 objectForKey:@"lastModDate"]]; (5认同)

Iva*_*vic 20

这个怎么样:

// Application documents directory
NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];

NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:documentsURL
                                                          includingPropertiesForKeys:@[NSURLContentModificationDateKey]
                                                                             options:NSDirectoryEnumerationSkipsHiddenFiles
                                                                               error:nil];

NSArray *sortedContent = [directoryContent sortedArrayUsingComparator:
                        ^(NSURL *file1, NSURL *file2)
                        {
                            // compare
                            NSDate *file1Date;
                            [file1 getResourceValue:&file1Date forKey:NSURLContentModificationDateKey error:nil];

                            NSDate *file2Date;
                            [file2 getResourceValue:&file2Date forKey:NSURLContentModificationDateKey error:nil];

                            // Ascending:
                            return [file1Date compare: file2Date];
                            // Descending:
                            //return [file2Date compare: file1Date];
                        }];
Run Code Online (Sandbox Code Playgroud)

  • 我自己只是在寻找解决方案,最后使用上面的代码.所以我把它放在这里因为我认为它比其他人提供的更干净;) (11认同)

小智 10

更简单...

NSArray*  filelist_sorted;
filelist_sorted = [filelist_raw sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSDictionary* first_properties  = [[NSFileManager defaultManager] attributesOfItemAtPath:[NSString stringWithFormat:@"%@/%@", path_thumb, obj1] error:nil];
    NSDate*       first             = [first_properties  objectForKey:NSFileModificationDate];
    NSDictionary* second_properties = [[NSFileManager defaultManager] attributesOfItemAtPath:[NSString stringWithFormat:@"%@/%@", path_thumb, obj2] error:nil];
    NSDate*       second            = [second_properties objectForKey:NSFileModificationDate];
    return [second compare:first];
}];
Run Code Online (Sandbox Code Playgroud)


abu*_*sky 5

这太慢了

[[NSFileManager defaultManager]
                                attributesOfItemAtPath:NSFileModificationDate
                                error:&error];
Run Code Online (Sandbox Code Playgroud)

试试这段代码:

+ (NSDate*) getModificationDateForFileAtPath:(NSString*)path {
    struct tm* date; // create a time structure
    struct stat attrib; // create a file attribute structure

    stat([path UTF8String], &attrib);   // get the attributes of afile.txt

    date = gmtime(&(attrib.st_mtime));  // Get the last modified time and put it into the time structure

    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setSecond:   date->tm_sec];
    [comps setMinute:   date->tm_min];
    [comps setHour:     date->tm_hour];
    [comps setDay:      date->tm_mday];
    [comps setMonth:    date->tm_mon + 1];
    [comps setYear:     date->tm_year + 1900];

    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDate *modificationDate = [[cal dateFromComponents:comps] addTimeInterval:[[NSTimeZone systemTimeZone] secondsFromGMT]];

    [comps release];

    return modificationDate;
}
Run Code Online (Sandbox Code Playgroud)