2011-08-07 11 views
0

このウェブサイトの巨大なファンですが、それは私の最初の投稿です!iphoneのobjcでファイルの配列を作成し、変更日順にソート

ディレクトリにファイル名の配列があり、並べ替える必要があります。並べ替えについては何百もの投稿がありますが、変更日順に並べ替えるために使用できるものは見つかりませんでした。

ここまでは私のコードです。それは正常に私のテーブルビューにフィードファイルの配列を作成します。私はちょうどいないアルファベット順、更新日で、それをソートする必要があります。

//Create dictionary with attributes I care about and a fileList array 

     NSMutableArray *fileList = [[NSMutableArray alloc] initWithCapacity:10]; 
     NSDictionary *fileData = [NSDictionary dictionaryWithObjectsAndKeys:file, @"file", dateString, @"date", nil]; 

     [fileList addObject:fileData]; 

//I don't know how to sort this array by the "date" key! 

     NSArray   *files = [fm contentsOfDirectoryAtPath:folderPath error:NULL]; 
    //iterate through files array 
     for (NSString *file in files) { 
      NSString *path = [folderPath stringByAppendingPathComponent:file]; 
    //code to create custom object with contents of file as properties 
    //feed object to fileList, which displays it in the tableview 

私は私はそれについてオンラインで見つけることができるすべてを読んだが、私はちょうどこのソートがどのように動作するかを理解していません。並べ替える方法は4つありますが、辞書の日付キーで並べ替える方法と、ここでどのように実装するのですか?

ありがとうございます!

編集:

これを投稿して約5秒後に回答が見つかりました。私は必要なコードがあった。

NSSortDescriptor *aSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES]; 
[sortedFiles sortUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]]; 

ので愚か簡単に、私はこの上のすべての一日費やしてきました!

これが誰かを助けることを願っています!

+2

あなたが見つけたものを投稿し、それをdoinの代わりに受け入れられた回答としてマークする必要がありますあなたの質問のコンテキストではそうです。 – csano

+0

私は自分の投稿に答えることはできません。 – ntesler

答えて

1

だけ明確にするために、答えはした:

NSSortDescriptor *aSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES]; 
[sortedFiles sortUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]]; 
6

ちょうどそれを探している人のためのより完全なコードを提供するために:

NSFileManager * fm = [NSFileManager defaultManager]; 
NSArray * files = [fm contentsOfDirectoryAtURL:[NSURL URLWithString:@"/path/to/dir/"] includingPropertiesForKeys:[NSArray arrayWithObject:NSURLCreationDateKey] options:NSDirectoryEnumerationSkipsHiddenFiles error:nil]; 

if ((nil != files) && ([files count] > 0)){ 
    NSArray * sortedFileList = [files sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) { 
     NSDate * mDate1 = nil; 
     NSDate * mDate2 = nil; 
     if ([(NSURL*)obj1 getResourceValue:&mDate1 forKey:NSURLCreationDateKey error:nil] && 
      [(NSURL*)obj2 getResourceValue:&mDate2 forKey:NSURLCreationDateKey error:nil]) { 
      if ([mDate1 timeIntervalSince1970] < [mDate2 timeIntervalSince1970]) { 
       return (NSComparisonResult)NSOrderedDescending; 
      }else{ 
       return (NSComparisonResult)NSOrderedAscending; 
      } 
     } 
     return (NSComparisonResult)NSOrderedSame; // there was an error in getting the value 
    }]; 
} 

1の代わりにNSURLCreationDateKeyを使用することができ、他のキーがあります - - 完全なリストは「共通ファイルシステムリソースキー」セクションのNSURL Class Reference

関連する問題