2011-11-02 10 views
6

私はすべてのファイルをiディレクトリに取得し、作成日または変更日に従ってソートしようとしています。そこには多くの例がありますが、私は彼らの誰も働かせることができません。作成日順にファイルを並べ替える - iOS

ディレクトリからファイルの配列を取得する方法は誰ですか?

+0

http://stackoverflow.com/questions/1523793/get-directory-contents-in-date-modified-order is this?あなたはNSFileCreationDateをNSFileModificationDateの代わりに使うことができると思います。 –

答えて

5

ここでは、作成日のファイルのリストを取得し、並べ替える2つの手順があります。

後でそれらをソートすることを容易にするために、私はその変更日とパスを保持するオブジェクトを作成します。

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

@implementation PathWithModDate 
@end 

さて、ファイルとフォルダのリスト(ない深い検索を取得します私はPathWithDateオブジェクトの配列を作成したら、私は(私は)降順選択した正しい順序でそれらを置くためにsortUsingComparatorを使用することを

- (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; 
} 

注:)、これを使用します。代わりに作成日を使用するには、代わりに[attr objectForKey:NSFileCreationDate]を使用してください。

+0

素晴らしい、ありがとう。 –

+0

PathWithModDateの代わりにNSDictionaryを使用できます。そのためのクラスを宣言する必要はありません。 – Flax

関連する問題