我有一个包含大量图像的应用程序。我想检查 bundle 中是否存在图像。如果是,我会显示它,如果不是,我会显示替换图像。
下面的代码是我想出的,但是它不起作用。任何人都可以发现问题所在吗?
谢谢!
NSString * photo = [NSString stringWithFormat:@"%d.jpg", UniqueID];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:photo];
if([fileManager fileExistsAtPath:path])
{
[image setImage:[UIImage imageNamed:photo]];
}
else {
NSLog(@"Hello");
[image setImage:[UIImage imageNamed:@"iPhoneHD.png"]];
}
编辑 - 根据以下 Simon 的帖子进行了更改,但仍然无法正常工作。 Else 语句始终触发。
最佳答案
您正在查看应用程序的文档目录。这真的是您期望找到图像的地方吗?如果它们实际上是添加到您的包中的资源,那么您需要这样做:
NSString *path = [[NSBundle mainBundle] pathForResource:uniqueID ofType:@"jpg"];
更简单 - 只需尝试加载指定的图像。如果失败,则加载默认值:
UIImage *tempImage = [UIImage imageNamed:photo];
if (!tempImage) {
tempImage = [UIImage imageNamed:@"iPhoneHD.jpg"]
}
[image setImage:tempImage];
关于iphone - 检查 bundle 中是否存在图像 - iPhone,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7931315/