【发布时间】:2011-11-22 20:02:32
【问题描述】:
从我看到的所有示例中,我确实相信我做对了。这是我的代码:
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0];
NSString* thisImage = [documentsPath stringByAppendingPathComponent:image_path];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:thisImage];
if (fileExists){
hotel_image = [UIImage imageNamed:image_path];
}else{
hotel_image = [UIImage imageNamed:@"hdrHotels.jpg"];
}
您可以假设“image_path”等于“images/hotels/thishotel.jpg”。
现在首先,让大家明白,“hdrHotels.jpg”在基本目录中。而“images/hotels/thishotel.jpg”是实际的子目录(蓝色文件夹)。我也试过使用:
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *imagePath = [NSString stringWithFormat:@"/%@",image_path];
NSString* thisImage = [documentsPath stringByAppendingPathComponent:imagePath];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:thisImage];
在“images/hotels/thishotel.jpg”前面添加一个前导“/”。在这两种情况下,无论图像是否存在,“if”语句都是错误的。我不确定我做错了什么。任何帮助将不胜感激。
编辑:
我变了:
NSString *imagePath = [NSString stringWithFormat:@"/%@",image_path];
到:
NSString *imagePath = [image_path stringByReplacingOccurrencesOfString:@"images/hotels/" withString:@""];
但还是不行。
我也试过了:
NSFileManager* fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString* documentsDir = [paths objectAtIndex:0];
NSString* myFilePath = [NSString stringWithFormat:@"%@/%@", documentsDir, image_path];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:myFilePath];
没有运气。
---------------------- 答案 ------------ --------------------
是的,我终于想通了。由于我还没有 100 个代表,所以我无法回答我自己的问题,但这是解决方法。
NSFileManager* fileManager = [NSFileManager defaultManager];
NSString *myFilePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:image_path];
BOOL fileExists = [fileManager fileExistsAtPath:myFilePath];
if (fileExists){
hotel_image = [UIImage imageNamed:image_path];
}else{
hotel_image = [UIImage imageNamed:@"hdrHotels.jpg"];
}
【问题讨论】:
标签: iphone objective-c file-exists