2012-07-26 77 views

回答

5

此代碼將枚舉所有文件在你的文件目錄下創建它們的順序:

見註釋中的代碼,瞭解正在發生的事情。

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); 
} 
+0

謝謝。它的工作:) – hoangpx 2012-07-28 13:37:31

+0

很高興看到如何加載所有文件與他們的屬性在一個單一的請求 – tothemario 2015-10-02 00:53:47