【问题标题】:Can't load images from "Documents" folder in iPhone/iPhone Simulator无法从 iPhone/iPhone 模拟器中的“文档”文件夹加载图像
【发布时间】:2014-12-03 23:31:57
【问题描述】:

我有一部分应该将图像保存到我手机的“文档”文件夹中,然后访问它。它保存得很好,但是加载方法并没有真正起作用。这是我的 .m 代码:​​

- (UIImage*)loadImage
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                             NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *path = [documentsDirectory stringByAppendingPathComponent:
                          @"photo.png" ];
        UIImage *image = [UIImage imageWithContentsOfFile:path];
        return image;
        studentImage = [[UIImageView alloc] initWithImage: image]; //UIImageView property
    }

- (UIImage*)loadBarcode
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString* path = [documentsDirectory stringByAppendingPathComponent:
                          @"barcode.png" ];
        NSLog(@"%@", path);
        UIImage *image = [UIImage imageWithContentsOfFile:path];
        return image;
        barcode = [[UIImageView alloc] initWithImage: image]; // UIImageView property 
    }

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self loadBarcode];
    [self loadImage];

}

文件肯定可以访问,文件路径是正确的。但是我试图将它们分配给空白的 UIImageViews。我的选择已经不多了。你们对它可能是什么有什么建议吗?

【问题讨论】:

  • 手动去文件路径打开图片,真的有内容吗?
  • 您有返回类型为 UIImage 的方法,但您没有使用这些方法的返回对象。这些方法中的最后一行也不会执行,因为您在最后一行之前返回。
  • return image 语句应该在你的代码中将 image 设置为 imageview 之后。而且也不需要 return 语句,因为您在调用函数时没有使用。将该函数设为 (void)

标签: ios objective-c file


【解决方案1】:

loadImage方法中,问题出在:

return image;
studentImage = [[UIImageView alloc] initWithImage: image];

您首先使用return 语句来转移控制权,并且从不将其分配给UIImageView 控制权。

应该是这样的:

studentImage = [[UIImageView alloc] initWithImage: image];
return image;

还有一点,如果studentImage通过IB连接,DON'T re-allocate it。而是使用:

studentImage.image = image;

希望对你有帮助!

【讨论】:

  • 这帮我找到了答案!我把我的属性搞砸了,这影响了我的代码。非常感谢您的回答!
【解决方案2】:

问题现已解决,我的属性名称有问题,但感谢您帮助我清理代码!

【讨论】:

    猜你喜欢
    • 2012-03-14
    • 2010-11-04
    • 2011-03-03
    • 2018-12-23
    • 2012-11-13
    • 2023-04-05
    • 2011-04-16
    • 2011-10-11
    • 1970-01-01
    相关资源
    最近更新 更多