Question

I have an iOS application that uses a simple UIDocument model with a single content field for iCloud storage. I retrieve the list of documents to populate a UITableView using an NSMetadataQuery. I want to have new documents appear at the top of this table, but the default sorting appears to be old -> new.

I know if I had a custom date field in the document I could sort the query with the NSSortDescriptor on that field but my question is is it possible to sort by the intrinsic modification date of the file created through the UIDocument iCloud storage? Or is there another preferred method to do this?

Was it helpful?

Solution

Looks like the right way to do this would be to set the sort descriptor of your query when you create it. Something along these lines:

NSMetadataQuery *query = [[NSMetadataQuery alloc] init];
[query setSearchScopes:[NSArray arrayWithObject:
                            NSMetadataQueryUbiquitousDocumentsScope]];

NSPredicate *pred = [NSPredicate predicateWithFormat: @"%K ENDSWITH '.bin'", 
                                   NSMetadataItemFSNameKey];
[query setPredicate:pred];

NSSortDescriptor *sortDescriptor = 
    [[[NSSortDescriptor alloc] initWithKey:NSMetadataItemFSContentChangeDateKey 
                                 ascending:FALSE] autorelease]; //means recent first
NSArray *sortDescriptors = [NSArray arrayWithObjects:
                                sortDescriptor,
                                nil];        
[query setSortDescriptors:sortDescriptors];

[[NSNotificationCenter defaultCenter] 
     addObserver:self 
     selector:@selector(queryDidFinishGathering:) 
     name:NSMetadataQueryDidFinishGatheringNotification 
     object:query];

[query startQuery];

OTHER TIPS

Gist: How about calling -[NSURL getResourceValue:forKey:error:] and passing in the NSURLContentModificationDateKey, then doing a descending sort on the returned NSDate values.

Details: You could either pass in a comparator to -[NSMutableArray sortUsingComparator:] that fetches the required NSDate for each object on the fly, or fetch them all into a new array with a compound NSDate, id object, and sort the array of that object, then extract the id references when done sorting (the python decorate-sort-undecorate idiom).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top