Sort files on iOS

December 4th, 2011

code snippet to sort files on the iOS

	NSFileManager *fileMgr = [NSFileManager defaultManager];
	
	NSArray *fileArray = [fileMgr contentsOfDirectoryAtURL:folderUrl
						includingPropertiesForKeys:[NSArray arrayWithObject:NSURLCreationDateKey]
										   options:NSDirectoryEnumerationSkipsHiddenFiles
											 error:nil];
	
	NSArray *sortedFiles = [fileArray sortedArrayUsingComparator:^(NSURL *url1, NSURL *url2) {
		NSDate *date1, *date2;
		
		// This works on iOS 5.
		[url1 getResourceValue:&date1 forKey:NSURLCreationDateKey error:nil];
		[url2 getResourceValue:&date2 forKey:NSURLCreationDateKey error:nil];
		if (date1 != nil && date2 != nil) {
			return [date2 compare:date1];
		}
		
		// On iOS 4 or earlier, the above getResourceValue won't work.
		date1 = [[fileMgr attributesOfItemAtPath:url1.path error:nil]
				 objectForKey:NSFileCreationDate];
		date2 = [[fileMgr attributesOfItemAtPath:url2.path error:nil]
				 objectForKey:NSFileCreationDate];
		return [date2 compare:date1];
	}];


2 Responses to “Sort files on iOS”

  1. Kris Roberts says:

    Thats great, and works fine but I’ve been trying to figure out how to sort with the result array in the other order. The routine above produces an array thats sorted with the oldest elements first – how do you get an array with the newest ones first?

    The alternate search mechanism seems to be using a descriptor, which you can specify ascending/descending – but doesn’t work with the resource key values in the nsurls.

    I’m feeling like I must be missing something, this can’t be hard to accomplish.

  2. Wei says:

     return [date2 compare:date1];
    Would change that to return [date1 compare:date2] works?

RSS feed for comments on this post. And trackBack URL.

Leave a Reply