Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Iphone 从资源文件夹中获取以前缀开头的所有文件名_Iphone_Objective C - Fatal编程技术网

Iphone 从资源文件夹中获取以前缀开头的所有文件名

Iphone 从资源文件夹中获取以前缀开头的所有文件名,iphone,objective-c,Iphone,Objective C,如何从资源文件夹中获取以前缀开头的所有文件名 您可以通过调整以下代码来实现这一点: NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath: [[NSBundle mainBundle] bundlePath] error:nil]; NSArray *pngs = [files filteredArrayUsingPredicate:

如何从资源文件夹中获取以前缀开头的所有文件名

您可以通过调整以下代码来实现这一点:

NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:
                  [[NSBundle mainBundle] bundlePath] error:nil];
NSArray *pngs = [files filteredArrayUsingPredicate:
                 [NSPredicate predicateWithFormat:@"self ENDSWITH[cd] '.png'"]];
NSLog(@"%@", pngs);
运行此代码,您将看到捆绑包上的PNG列表。将谓词更改为与所需前缀匹配:

NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:
                  [[NSBundle mainBundle] bundlePath] error:nil];
NSArray *filesWithSelectedPrefix = [files filteredArrayUsingPredicate:
                                    [NSPredicate predicateWithFormat:@"self BEGINSWITH[cd] 'prefix'"]];
NSLog(@"%@", filesWithSelectedPrefix);

为Swift 4.0更新:

在我的例子中,我正在寻找以
fileName-1.png
开头的文件,其中可能有其他以
fileName
前缀的文件

1) 我曾考虑过使用正则表达式,但是拆分字符串更快更容易,所以我选择了这种方法来获取前缀

let myKnownFileNameString = "fileName-1.png"
let filePrefix = myKnownFileNameString.split(separator: "-").first
2) 创建空数组以存储找到的图像:

var imageArray: [UIImage] = []
3) 然后,从捆绑包中获取URL,
filter
它们和
map
将URL映射到
UIImage
实例:

if let filePrefix = filePrefix, let fileURLs = Bundle.main.urls(forResourcesWithExtension: "png", subdirectory: nil) {
    imageArray = fileURLs.filter{ $0.lastPathComponent.range(of: "^\(filePrefix)", options: [.regularExpression, .caseInsensitive, .diacriticInsensitive]) != nil }
                         .map{ UIImage(contentsOfFile: $0.path)! }
}
从那里,您可以使用一组图像(在
UIImageView
中对它们进行动画制作等)

有更合适、更快捷的方法,例如,您可以使用
Bundle.main.url(对于ResourceswitExtension:“png”,子目录:nil)获取具有给定扩展名的所有URL
使用
而不是
NSPredicate
使用
过滤器{$0.range(of:“^\(filePrefix)”,选项:[.regularpression、.case不敏感、.diacriticInsensitive])!=nil}