2011-11-02 167 views
6

我試圖獲取i目錄中的所有文件,並根據創建日期或修改日期對它們進行排序。這裏有很多例子,但我不能讓他們中的任何一個人去工作。按創建日期排序文件 - iOS

任何人都有一個很好的例子如何從日期排序的目錄中獲取文件數組?

+0

http://stackoverflow.com/questions/1523793/get-directory-contents-in-date-modified-order是這樣嗎?我想你可以使用NSFileCreationDate而不是NSFileModificationDate –

回答

5

這裏有兩個步驟,獲取具有創建日期的文件列表並對它們進行排序。

爲了使它容易對他們再整理,我創建一個對象來與它的修改日期舉行的路徑:

@interface PathWithModDate : NSObject 
@property (strong) NSString *path; 
@property (strong) NSDate *modDate; 
@end 

@implementation PathWithModDate 
@end 

現在,讓文件和文件夾(列表中未深的搜索),使用此:

- (NSArray*)getFilesAtPathSortedByModificationDate:(NSString*)folderPath { 
    NSArray *allPaths = [NSFileManager.defaultManager contentsOfDirectoryAtPath:folderPath error:nil]; 

    NSMutableArray *sortedPaths = [NSMutableArray new]; 
    for (NSString *path in allPaths) { 
     NSString *fullPath = [folderPath stringByAppendingPathComponent:path]; 

     NSDictionary *attr = [NSFileManager.defaultManager attributesOfItemAtPath:fullPath error:nil]; 
     NSDate *modDate = [attr objectForKey:NSFileModificationDate]; 

     PathWithModDate *pathWithDate = [[PathWithModDate alloc] init]; 
     pathWithDate.path = fullPath; 
     pathWithDate.modDate = modDate; 
     [sortedPaths addObject:pathWithDate]; 
    } 

    [sortedPaths sortUsingComparator:^(PathWithModDate *path1, PathWithModDate *path2) { 
     // Descending (most recently modified first) 
     return [path2.modDate compare:path1.modDate]; 
    }]; 

    return sortedPaths; 
} 

需要注意的是,一旦我創建PathWithDate對象的數組,我用sortUsingComparator把他們按正確的順序(我選擇降序)。爲了使用創建日期,請改用[attr objectForKey:NSFileCreationDate]

+0

真棒,謝謝。 –

+0

您可以使用NSDictionary而不是PathWithModDate。無需爲此申報班級。 – Flax