Quote:
Originally Posted by Objective Zero
Hey,
Is it possible to create a NSArray out of all .png, .jpg, and .jpeg that are all in my app? I know it is possible to do it to a certain type like only .pngs but I am not sure how to do it to all images in my app.
So this is the code I am using and I put it in my ViewDidLoad because that is where I want to fill up my array but the issue is that, according to my NSLogs it is only reaching NSLog "Level1" and it never reaches level 3 thus, my array is nil and causes my app to crash. I have a 'images' group in my Xcode project not a folder if that makes any difference.
Code:
// Do any additional setup after loading the view, typically from a nib.
NSString * pathToImages = [NSString stringWithFormat: @"%@/images", [[NSBundle mainBundle]
]];
NSFileManager *localFileManager= [[[NSFileManager alloc] init] autorelease];
NSDirectoryEnumerator *dirEnum = [localFileManager enumeratorAtPath:pathToImages];
NSString *file;
NSLog(@"level1");
while (file = [dirEnum nextObject]) {
NSLog(@"level2");
if(file)
{
NSLog(@"level3");
[imagesArray addObject:file];
}
}
Does anyone have any ideas why this is not working?
Thanks!
|
There's lots of problems with your code.
1. Don't create an instance of NSFileManager. Use the class method defaultManager to get a pointer to the shared file manager object.
2. Don't use the file manager at all. Use one of the NSBundle method for listing the contents of a bundle, like pathsForResourcesOfType:inDirectory, or URLsForResourcesWithExtension:subdirectory:
If you have several different types of image files, you will need to call the method repeatedly for each filetype.
You could also get the path to the main bundle's resources directory, use the NSString method "stringByAppendingPathComponent" to add your "/images/" subdirectory to the path, and use the file manager method contentsOfDirectoryAtPath:error to get a list of all the files in the directory. You'd then need to use the NSString method lastPathComponent on each path in the array to get rid of all the path info and get just the filename for each file.