从文档目录加载已保存的图像

Aud*_*udi 2 objective-c nsdocument ios

我使用这里给出的代码来保存和加载图像

当我在一个视图控制器中一起使用它时工作正常,但是当我在一个视图控制器中使用saveImage方法并尝试在另一个视图控制器中加载图像时,图像返回空白...

在视图控制器A中,我使用以下内容保存图像

- (void)saveImage: (UIImage*)image
{
    NSLog(@"saveimage called");

    if (image != nil)
    {
        NSLog(@"Image not null");
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                             NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString* path = [documentsDirectory stringByAppendingPathComponent:
                          @"test.png" ];
        NSData* data = UIImagePNGRepresentation(image);
        [data writeToFile:path atomically:YES];
        QrImageView.image = nil;
    }
}
Run Code Online (Sandbox Code Playgroud)

并在视图控制器说B我正在使用..加载图像..

- (UIImage*)loadImage
{
    NSError *error;

    NSFileManager *fileMgr = [NSFileManager defaultManager];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString* path = [documentsDirectory stringByAppendingPathComponent:
                      @"test.png" ];
    UIImage* image = [UIImage imageWithContentsOfFile:path];

    // Write out the contents of home directory to console
    NSLog(@"Documents directory: %@", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);

    return image;
}
Run Code Online (Sandbox Code Playgroud)

我也在控制台中获取文件的内容,但我不明白为什么图像是空白的

2013-07-06 14:13:19.750 YouBank[500:c07] Documents directory: (
    "test.png"
)
Run Code Online (Sandbox Code Playgroud)

知道我做错了什么......

EDIT:
Run Code Online (Sandbox Code Playgroud)

在viewDidload方法的视图控制器B中,我执行以下操作

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    ImageView.image=[self loadImage];
    ImageName.text = @"Cash Withdrawal";
}
Run Code Online (Sandbox Code Playgroud)

Sta*_*ash 6

问题是你只在viewDidLoad上用UIImage更新你的UIImageView.一旦从文件系统中获取更新,您需要添加更新(最好是在后台线程上).所以它看起来像这样:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^{
    UIImage *loadedImage = [self loadImage];
    dispatch_async(dispatch_get_main_queue(),^{
         ImageView.image = loadedImage;
    });
});
Run Code Online (Sandbox Code Playgroud)

我还建议使用以小写字符开头的名称作为实例名称,因此您应该重命名ImageView - > imageView