简体   繁体   中英

get file names to NSArray

I have images in Images folder, and i would like to initialize an array with strings of file name...

ex:

one.png, two.png, three.png

I would like to initialize my array as ["one", "two", "three"]

Try this:

//Retrieve an array of paths in the given directory
NSArray *imagePaths = [[NSFileManager defaultManager] contentsOfDirectoryAtPath: @"/Images/" error: NULL];

if(imagePaths==nil || [imagePaths count]==0) {
    //Path either does not exist or does not contain any files
    return;
}

NSEnumerator *enumerator = [imagePaths objectEnumerator];
id imagePath;
NSString *newImageName;

NSMutableArray *imageNames = [[NSMutableArray alloc] init];

while (imagePath = [enumerator nextObject]) {
    //Remove the file extension
    newImageName = [imagePath stringByDeletingPathExtension];
    [imageNames addObject:newImageName];
}

The first part of the code retrieves the names of the files in the given directory, and adds them to the imagePaths array.

The second part of the code then loops over the image paths in the array and removes the extension from the end (using the stringByDeletingPathExtension method), appending them to the imageNames array, which will contain all the files in the given directory without any file extensions.

As Graham Lee has done in his code, you could provide a pointer to an NSError object to obtain information about the problem, should an error arise.

NSError *error = nil;
NSArray *imageFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath: @"/path/to/Images/" error: &error];
if (imageFiles == nil) //handle the error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM