【问题标题】:Save Image Path to NSDocuments then retrieve it as a UIImage将图像路径保存到 NSDocuments 然后将其检索为 UIImage
【发布时间】:2018-07-05 20:40:45
【问题描述】:

我有一个图像选择器控制器,它将选定的图像存储到一个目录中。我能够很好地保存路径,但检索它们会导致崩溃。我不确定要保存的代码是错误的还是要检索的代码是错误的。这是崩溃错误。

*** 由于未捕获的异常而终止应用程序 'NSInvalidArgumentException',原因:'-[__NSCFString 大小]:无法识别 选择器发送到实例 0x1c484bc40'

这是检索文件并存储在NSMutableArray 中的代码。这就是崩溃发生的地方。我需要路径的结果是UIImage 文件。

- (void)loadCustomDesignGIFEdit:(TSPEventRepository *)record {
    NSError *error = nil;
    NSMutableArray *arrSlidshowImg = @[].mutableCopy;
    NSString *Dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
    NSUserDomainMask, YES) objectAtIndex:0];
    NSString *path = [NSString stringWithFormat:@"%@%@",Dir, @"/Images/"];
    NSArray * directoryContents = [[NSFileManager defaultManager]
     contentsOfDirectoryAtPath:path error:&error];
    UIImage *image = [UIImage imageWithContentsOfFile:path];

    for (image in directoryContents) {
        [arrSlidshowImg addObject:image];
    }
    NSLog(@"ARRAY RESULT: %@", arrSlidshowImg);

    fourBySixBackgroundImageViewGIF.image = [arrSlidshowImg objectAtIndex:0];      
}

当我按下按钮调用loadCustomDesignGIFEdit 时,日志显示了我选择的图像的正确路径,但它崩溃了。我需要它将路径作为带有 PNG 表示的图像保存到 NSMutableArray 中。

这是日志结果:

数组结果:( "picName_IMG_7293.JPG", “picName_IMG_7294.JPG” )

【问题讨论】:

  • 不相关,但我建议不要手动连接路径字符串,例如 [NSString stringWithFormat:@"%@%@", directory, @"/Images/"];。我建议[directory stringAppendingPathComponent:@"Images"]NSString 提供了一堆路径和 URL 函数,所以你不必担心斜杠必须插入到哪里...

标签: ios objective-c uiimageview nsfilemanager


【解决方案1】:

有一句话说:

UIImage *image = [UIImage imageWithContentsOfFile:path]

这没有意义,因为path 是文件夹的路径,而不是任何特定图像的路径。

但是您的神秘错误源于以下代码行:

fourBySixBackgroundImageViewGIF.image = [arrSlidshowImg objectAtIndex:0];

不幸的是,arrSlidshowImg 是一个字符串数组,而不是图像数组。因此,当您将其作为UIImageViewimage 提供时,该错误神秘地告诉您它正在尝试检索图像的size,但您提供的NSString 没有这样的方法/属性。

你的意思可能是:

NSString *filename = arrSlidshowImg[0];
NSString *imagePath = [path stringAppendingPathComponent:filename];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
fourBySixBackgroundImageViewGIF.image = image;

【讨论】:

  • 两行代码让我伤心了一个小时。太感谢了。效果很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-23
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 2020-08-22
  • 1970-01-01
相关资源
最近更新 更多