Sorted NSFileManager content

Discussion in 'Mac Programming' started by UruLama, Jun 6, 2008.

  1. UruLama macrumors newbie

    Joined:
    Jun 6, 2008
    #1
    Hi, all.

    I would like to get the list of filenames in a current directory sorted by the date of the modification (from the most recent to the odlest). The following code returns only the files in the directory:

    NSArray* dirCont = [fm directoryContentsAtPath: [fm currentDirectoryPath]];

    Is there a way to get the filenames in dirCont sorted by some file attribute (for example NSFileModificationDate) directly without sorting the content on hand?

    TNX, UruLama.
     
  2. indiekiduk macrumors 6502

    Joined:
    Jul 26, 2005
    Location:
    Glasgow, Scotland
    #2
    I'd like to know this too? Here is a long way:

    Code:
    -(NSString*)findLatestFileInDir:(NSString*)dir{
    	
    	NSFileManager *fileManager = [NSFileManager defaultManager];
    	NSArray* contents = [fileManager directoryContentsAtPath:dir];
    	NSDictionary *currentFileAttributes;
    	NSDate* currentFileDate;
    	NSString* latestFile;
    	NSDate* latestFileDate = [NSDate distantPast];
    	for (NSString* fname in contents) {
    		//check file is newer
    		currentFileAttributes = [fileManager fileAttributesAtPath:[NSString stringWithFormat:@"%@/%@",dir,fname] traverseLink:YES];
    		currentFileDate = [currentFileAttributes objectForKey:NSFileModificationDate];
    		if([currentFileDate laterDate:latestFileDate] == currentFileDate){
    			latestFileDate = currentFileDate;
    			latestFile = fname;
    		}
    	}
    	return latestFile;
    }
     

Share This Page