是否可以使用我的应用程序中的所有 .png、.jpg 和 .jpeg 创建 NSArray?我知道可以对某种类型执行此操作,例如仅 .png,但我不确定如何对我的应用程序中的所有图像执行此操作。
我不想有很多条件,所以我怎样才能轻松做到这一点?
谢谢!
编辑1:
// Do any additional setup after loading the view, typically from a nib.
NSString * pathToImages = [NSString stringWithFormat: @"%@/images", [[NSBundle mainBundle] resourcePath]];
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];
}
}
最佳答案
取决于您希望如何在数组中存储图像。您想要文件引用还是实际的 UIImage 对象?
无论如何...如果您将所有图像保存在应用程序资源目录中的“images”文件夹中,为什么不尝试以下操作:
NSString * pathToImages = [NSString stringWithFormat: @"%@/images", [[NSBundle mainBundle] resourcePath]];
NSFileManager *localFileManager= [[NSFileManager alloc] init];
NSDirectoryEnumerator *dirEnum = [localFileManager enumeratorAtPath:docsDir];
NSMutableArray * arrayOfImages = [[NSMutableArray alloc] initWithCapacity: 1];
NSString *file;
while (file = [dirEnum nextObject]) {
// let's assume that all objects in here are valid images
UIImage * newImage = [UIImage imageWithContentsOfFile: file];
if(newImage)
{
[arrayOfImages addObject: newImage];
}
}
顺便说一句...如果您正在加载大量图像(尤其是高分辨率图像),您可能会遇到 didReceiveMemoryWarning
在 View Controller 中调用。
关于ios - 从应用程序中的所有图像创建数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8453710/