Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get an NSArray of filenames of all files in a given directory in my app?

What I want to do seems simple enough: Get an array of filenames in a given "directory" on my app. But the more I play around with NSFileManager and NSBundle I find myself getting more lost...I just want to get the filenames of the files organized in a specific directory in my iPhone Xcode project...For example: The directory in question is called "Images" (created using "Add > New Group" under the project icon in Xcode) and contains 10 .png images. It seems simple but I am getting nowhere. I'd appreciate some help in finding the answer.

Q: How do I get an NSArray of filenames of all files in a given directory in my app?

like image 573
RexOnRoids Avatar asked Aug 13 '09 13:08

RexOnRoids


People also ask

How do you read the filenames of all the files in a directory into an array?

You can use the Dir$ function to do this. (Dir and Dir$ are functionally identical, but Dir$ runs marginally faster).


3 Answers

If you want the folder to be part of the App bundle, you need to create a folder reference inside the Resources group, instead of a group (it will show up in Xcode as a blue folder as opposed to the yellow one).

To do this, you drag the folder from Finder and select folder reference when prompted.

Once you have that, you should be able to get the contents of the folder with something like:

NSError *error = nil;

NSString *yourFolderPath = [[[NSBundle mainBundle] resourcePath]
                            stringByAppendingPathComponent:@"YourFolder"];

NSArray  *yourFolderContents = [[NSFileManager defaultManager] 
                                contentsOfDirectoryAtPath:yourFolderPath error:&error];
like image 167
pgb Avatar answered Oct 26 '22 06:10

pgb


The accepted answer's been deprecated for years now. The following should be used instead.

- (NSArray *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error

Update: @macserv updated the accepted answer after I posted this.

like image 36
james_womack Avatar answered Oct 26 '22 04:10

james_womack


Nowadays, this is how you do it:

  1. From the Finder, Drag & Drop your folder in your project's navigator and the next popup will show up: enter image description here
  2. As you can see in that screenshot, you have to select Create folder references.
  3. Do what the solution for this post is tells you to do. I mean:

    NSError *error = nil;

    NSString *yourFolderPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"YourFolder"];

    NSArray *yourFolderContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:yourFolderPath error:&error];

like image 45
jmoukel Avatar answered Oct 26 '22 05:10

jmoukel