简体   繁体   English

获取NSArray的文件名

[英]get file names to NSArray

I have images in Images folder, and i would like to initialize an array with strings of file name... 我在Images文件夹中有图像,我想初始化一个包含文件名字符串的数组...

ex: 例如:

one.png, two.png, three.png one.png,two.png,three.png

I would like to initialize my array as ["one", "two", "three"] 我想将我的数组初始化为[“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. 代码的第一部分检索给定目录中文件的名称,并将它们添加到imagePaths数组中。

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. 然后代码的第二部分循环遍历数组中的图像路径并从末尾删除扩展(使用stringByDeletingPathExtension方法),将它们附加到imageNames数组,该数组将包含给定目录中的所有文件,没有任何文件扩展名。

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. 正如Graham Lee在他的代码中所做的那样,如果出现错误,您可以提供指向NSError对象的指针以获取有关该问题的信息。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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