Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort an icloud NSMetadataQuery result of UIDocument's by modification date?

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?

like image 863
Jason N Avatar asked Sep 09 '12 15:09

Jason N


1 Answers

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];
like image 88
dubemike Avatar answered Sep 24 '22 20:09

dubemike