Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting files (and its attributes) in a directory

I want to get a list of files within a directory but I need to know if the file is a directory, when it was last modified, and offcourse its name :) . So I tried this:

NSFileManager *fm = [NSFileManager defaultManager];
NSURL *directoryURL = [NSURL fileURLWithPath:@"/Users/nacho4d/Desktop/"];
NSArray *urls = [fm contentsOfDirectoryAtURL:directoryURL 
                      includingPropertiesForKeys:[NSArray arrayWithObjects:NSURLNameKey, NSURLIsDirectoryKey, NSURLContentModificationDateKey, nil] 
                                         options:NSDirectoryEnumerationSkipsHiddenFiles 
                                           error:nil];
NSError *error = nil;
NSString *name;
NSDate *modificationDate;
NSNumber *isDirectory;
for (NSURL *url in urls) {
    if (![url getResourceValue:&name forKey:NSURLNameKey error:&error]) {
        NSLog(@"name: %@", [error localizedDescription]);error = nil;
    }
    if (![url getResourceValue:&modificationDate forKey:NSURLContentModificationDateKey error:&error]) {
        NSLog(@"modificationDate: %@", [error localizedDescription]); error = nil;
    }
    if (![url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:&error]) {
        NSLog(@"isDirectory: %@", [error localizedDescription]); error = nil;
    }
    NSLog(@"%@ %@ %@", name, modificationDate, isDirectory);
}

However I always get (null) (null) (null), no errors but no data ;(

I wonder what is wrong here?

PS: I am aware of contentsOfDirectoryAtPath:error: and attributesOfItemAtPath:error: but I think that is not the best way of doing this, is it? I plan to use this in folders that can contain a large number of files so I would like to do this the most efficient way possible.

Edit for iOS5 and later

As @jeremyP pointed, According to the docs the method is unimplemented in iOS4 but since iOS5 and later it seems to work properly:

Availability
Available in iOS 5.0 and later. (Symbol is present in iOS 4, but performs no operation.)

This question was done when iOS4 was the latest I think. Now in iOS 5 and 6 Everything works as expected :)

like image 285
nacho4d Avatar asked Jul 05 '11 14:07

nacho4d


1 Answers

This isn't the answer to your question but your error checking should look like this:

if (![url getResourceValue:&name forKey:NSURLNameKey error:&error])
{
    NSLog(@"name: %@", [error localizedDescription]);error = nil;
}

Edit

Couldn't figure out what the problem was, but have just reread the documentation on the method. The important sentence is the one under discussion that says:

This method is unimplemented in iOS, so it performs no operation.

like image 62
JeremyP Avatar answered Oct 27 '22 00:10

JeremyP