NSFileManager在文件夹中搜索图像文件

时间:2013-01-31 02:56:39

标签: ios objective-c nsfilemanager

我正在使用NSFileManager搜索“index.png”文件。如果文件不存在,那么我试图显示默认图像。我使用下面的代码,但它无法正常工作。我在这里做错了吗?

NSString *path;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString path1 = [[paths objectAtIndex:0] stringByAppendingPathComponent:literature.localURL.path];
path = [path1 stringByAppendingPathComponent:@"index.PNG"];

    if ([[NSFileManager defaultManager] fileExistsAtPath:path]){
        cell.preview = [UIImage imageWithContentsOfFile:path1];
    }
    else {
        cell.preview = [UIImage imageNamed:@"Default-HTML5.PNG"];
    }
}

3 个答案:

答案 0 :(得分:1)

您将路径设置为两个不同的东西。为其中一个使用不同的字符串,例如

NSString *path1 = [[paths objectAtIndex:0] stringByAppendingPathComponent:literature.localURL.path];

并保持另一个

并制作“index.PNG”“index.png”。 iOS区分大小写。

答案 1 :(得分:1)

cell.preview = [UIImage imageWithContentsOfFile: path];

引用苹果文件:

imageNamed:
Returns the image object associated with the specified filename.

+ (UIImage *)imageNamed:(NSString *)name
Parameters
name
The name of the file. If this is the first time the image is being loaded, the method looks for an image with the specified name in the application’s main bundle.

你的png不是在主要包中,而是在你的文件夹中

imageWithContentsOfFile:
Creates and returns an image object by loading the image data from the file at the specified path.

答案 2 :(得分:0)

imageNamed: 

for images

  

该方法在应用程序的主包中查找具有指定名称的图像。

,对于文档目录,您必须使用

[UIImage imageWithContentsOfFile: path];

Guo Luchuan