【问题标题】:Checking if Image Exists in Bundle - iPhone检查图像是否存在于 Bundle - iPhone
【发布时间】:2011-12-17 09:28:34
【问题描述】:

我有一个包含许多图像的应用程序。我想检查捆绑中是否存在图像。如果是,我会显示它,如果不是,我会显示替换图像。

下面的代码是我想出的,但是它不起作用。谁能发现哪里出了问题?

谢谢!

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 语句总是触发。

【问题讨论】:

    标签: iphone objective-c xcode sdk nsfilemanager


    【解决方案1】:

    您正在查看应用程序的 Documents 目录。这真的是您期望找到图像的地方吗?如果它们实际上是添加到您的捆绑包中的资源,那么您需要这样做:

    NSString *path = [[NSBundle mainBundle] pathForResource:uniqueID ofType:@"jpg"];
    

    更简单 - 只需尝试加载命名图像。如果失败则加载默认值:

    UIImage *tempImage = [UIImage imageNamed:photo];
    
    if (!tempImage) {
        tempImage = [UIImage imageNamed:@"iPhoneHD.jpg"]
    }
    
    [image setImage:tempImage];
    

    【讨论】:

    • 编辑回复以确认您是真的想查看 Documents 目录还是真的想要您的应用程序包。
    【解决方案2】:
    +(BOOL) fileExistsInProject:(NSString *)fileName
    {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *fileInResourcesFolder = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName];
        return [fileManager fileExistsAtPath:fileInResourcesFolder];
    }
    

    是我的答案。


    如果文件存在于 bundle 中则返回 YES。你不必对路径做任何事情。 只需说 [fileExistsInProject:@"blabla.ext"]

    【讨论】:

      【解决方案3】:

      你的 if 语句错误的方式,你说如果它不存在,那么使用它,否则使用默认的......你想要......

      if([fileManager fileExistsAtPath:path])
      

      【讨论】:

      • 嗨,西蒙。谢谢,但它仍然不起作用。每次都会触发 else 语句,即使文件存在。
      • 绝对可以。问题是您不能只将文件名作为路径传递。你需要这样的东西: [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"png"]
      猜你喜欢
      • 1970-01-01
      • 2012-06-09
      • 2021-07-02
      • 2011-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-10
      相关资源
      最近更新 更多