2011-10-28 106 views
16

我有一个应用程序的图像数量。我想检查包中是否存在图像。如果它显示,则显示替换图像。检查图片是否存在 - iPhone

下面的代码是我想出的,但它不起作用。任何人都可以发现什么是错的?

谢谢!

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的帖子,但仍然无法正常工作。其他语句总是触发。

回答

22

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

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

仍然更容易 - 只需尝试加载指定的图像。如果失败则加载默认:

UIImage *tempImage = [UIImage imageNamed:photo]; 

if (!tempImage) { 
    tempImage = [UIImage imageNamed:@"iPhoneHD.jpg"] 
} 

[image setImage:tempImage]; 
+0

编辑的响应以确认您是真的想要查看Documents目录还是实际需要您的应用程序包。 –

+0

谢谢 - 这工作。 – GuybrushThreepwood

6

你有if语句走错了路,你是说,如果它不存在,然后使用它,否则使用默认的.....你想...

if([fileManager fileExistsAtPath:path]) 
+0

嗨西蒙。谢谢,但它仍然无法正常工作。每次都会触发else语句,即使文件存在。 – GuybrushThreepwood

+0

它应该肯定工作。事情是你不能只传递文件名作为路径。您需要如下所示:[[NSBundle mainBundle] pathForResource:@“filename”ofType:@“png”] –

14
+(BOOL) fileExistsInProject:(NSString *)fileName 
{ 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSString *fileInResourcesFolder = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName]; 
    return [fileManager fileExistsAtPath:fileInResourcesFolder]; 
} 

就是我的回答。


如果文件存在于bundle中,则返回YES。您不必对路径执行任何操作。 只是说[fileExistsInProject:@“blabla.ext”]