Reputation: 465
I'm pretty new to Objective-C. I'm developing a Cocoa application. Currently I'm looking for the equivalent of this C# code in Objective C:
string[] fileList = Directory.GetFiles(DownloadPath, "*.jpg");
The returned strings need not necessarily be full path, since all I need is the file names. I have tried NSFileManager but so far no good yet. Thank you.
EDIT: What I've tried with NSFileManager:
[someFileManager contentsOfDirectoryAtPath:path error:nil];
I also want to ask: what is the format of 'path'? This sounds easy, but I'm completely clueless about MAC OS file system. The path that I'm using is from [NSOpenPanel URLs], and they looks like this:
file://localhost/Users/alex/Movies/
Sometimes I get the results, but some other time The returned NSArray is just empty. I'm pretty confused about this so any help would be appreciated.
EDIT2: The answer here: NSPredicate endswith multiple files, is probably a better choice. Nevertheless, thank you for your answer.
Upvotes: 25
Views: 22574
Reputation: 832
In fact you need some thing like this
NSArray *dirFiles = [fileManager contentsOfDirectoryAtURL:[NSURL fileURLWithPath:documentsDir] includingPropertiesForKeys:[NSArray array] options:0 error:nil] ;
NSArray *filteredFiles = [dirFiles filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self.absoluteString ENDSWITH '.jpg'"]] ;
Because contentsOfDirectoryAtURL: returns array of NSURL's, so using just "self ENDSWITH '.jpg'" will crash.
Upvotes: 4
Reputation: 1345
maybe something along these lines:
NSFileManager * fileMan = [[NSFileManager alloc] init];
NSArray * files = [fileMan contentsOfDirectoryAtPath:@"mypath/blah" error:nil];
if (files)
{
for(int index=0;index<files.count;index++)
{
NSString * file = [files objectAtIndex:index];
if( [[file pathExtension] compare: @"jpg"] == NSOrderedSame )
{
// do something with files that end with .jpg
}
}
}
[fileMan release];
Upvotes: 3
Reputation: 3294
This code should work:
NSArray *dirFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
NSArray *jpgFiles = [dirFiles filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self ENDSWITH '.jpg'"]];
Upvotes: 50