views:

148

answers:

1

I'm trying to create an array of NSStrings of the contents of a folder that I've dragged into my project... but when I count the items in the array afterwards, it's always comes back with 0;

So, my folder in my project looks like this

-Cards
  -Colors
     Blue.png
     Green.png
     Orange.png
     Yellow.png
     Purple.png
     Black.png

And my code which tries to get this list of files (the color pngs) is

NSError *error = nil;
NSString *pathString = [[NSString alloc] init];
pathString = [[NSString alloc] initWithString:@"/Cards/Colors/"];
NSArray *fileList = [[NSArray alloc] init];
fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:pathString error: &error];
[pathString release];
NSLog(@"%@", error);
// this is always 0
NSLog(@"file list has %i items", [fileList count]);

The NSError I get is

Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be completed. (Cocoa error 260.)" UserInfo=0x596db00 {NSUserStringVariant=(
    Folder
), NSFilePath=/Cards/Color/, NSUnderlyingError=0x5925ef0 "The operation couldn’t be completed. No such file or directory"}

Any ideads where I am going wrong?

+4  A: 

You're initializing pathString to the absolute path /Cards/Colors/. This path is a system-wide path, so on the iPhone, far outside your app's sandbox.

Try this instead:

NSString *pathString = [[NSBundle mainBundle] pathForResource:@"Cards/Colors" ofType:nil];
NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:pathString error: &error];

(Note that the way you have your code in the question, you alloc/init fileList, then immediately leak the object by assigning to it the results of contentsOfDirectoryAtPath:error:. This is a bug.)

Steve Madsen
Thanks, the pathString is null after the first line, and because of that I get a '*** Terminating app due to uncaught exception 'NSInvalidArgumentException'' on the next line. I wonder if I'm adding the folders correctly..?
cannyboy
It could be that. I don't think that an Xcode group automatically becomes a directory in the bundle. It could also be that `pathForResource:ofType:` doesn't work for directories. In that case, use `-[NSBundle bundlePath]` to get the path to the root of the bundle, then `-[NSString stringByAppendingPathComponent:]` to get to your subdirectory.
Steve Madsen