3
我有一個應用程序的文檔文件夾中的圖像列表,我想按創建日期的順序加載圖像。 我該怎麼做?IOS - 按順序加載本地文件
我有一個應用程序的文檔文件夾中的圖像列表,我想按創建日期的順序加載圖像。 我該怎麼做?IOS - 按順序加載本地文件
此代碼將枚舉所有文件在你的文件目錄下創建它們的順序:
見註釋中的代碼,瞭解正在發生的事情。
NSFileManager *fm = [NSFileManager defaultManager];
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSError *err;
// Get all files with their creation date
NSArray *files = [fm contentsOfDirectoryAtURL:[[NSURL alloc] initFileURLWithPath:doc isDirectory:YES]
includingPropertiesForKeys:[NSArray arrayWithObject:NSURLCreationDateKey]
options:0
error:&err];
// Using file's URL as the key, store creation date as the value
NSMutableDictionary *urlWithDate = [NSMutableDictionary dictionaryWithCapacity:files.count];
for (NSURL *f in files) {
NSDate *creationDate;
if ([f getResourceValue:&creationDate forKey:NSURLCreationDateKey error:&err]) {
[urlWithDate setObject:creationDate forKey:f];
}
}
// Sort the dictionary on the value, which is the creation key
for (NSURL *f in [urlWithDate keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [obj1 compare:obj2];
}]) {
// Check if the file is an image. Load if it is an image, otherwise skip.
NSLog(@"%@", f);
}
我會看看:Getting a list of files in a directory with a glob
具體的的NSFileManager。您可以查看文件的屬性。從那裏你很可能使用NSPredicate進行排序。
謝謝。它的工作:) – hoangpx 2012-07-28 13:37:31
很高興看到如何加載所有文件與他們的屬性在一個單一的請求 – tothemario 2015-10-02 00:53:47