iphone - 检查 bundle 中是否存在图像 - iPhone

标签 iphone objective-c xcode sdk nsfilemanager

我有一个包含大量图像的应用程序。我想检查 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/

相关文章:

ios - 是否有用于在 iPhone 应用程序中设置首选项的库或框架?

ios - objective-c - block 保留周期

iphone - iOS 版 OpenGL ES 1.0 中的单位如何设置?

ios - 实现按钮拖动动量?

javascript - 尝试获取 HTML 内容时被阻止

xcode - 如何根据用户与 iOS 中固定点的接近程度来限制用户操作?

ios - 为现有 AppStore 应用重命名 Xcode 项目

iphone - NSMutableArray 到字节数组到字符串

ios - 什么是恢复标识符?

ios - segue 在简单的 segue 测试中不起作用