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

南笙酒味 提交于 2019-12-07 00:36:09

问题


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?


回答1:


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];



回答2:


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).



来源:https://stackoverflow.com/questions/12340239/how-can-i-sort-an-icloud-nsmetadataquery-result-of-uidocuments-by-modification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!