在iOS上将文件写入文件系统时访问图像

时间:2013-03-06 09:04:33

标签: ios image filesystems file-exists

我的应用正在从网络加载一堆图像,并将它们保存到应用沙盒环境中的本地文件系统(FS)。当我将图像保存到FS时,我使用GCD这样做:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil];
    [UIImagePNGRepresentation(image) writeToFile:path atomically:YES];
});

这很好用。但是,当我尝试同时从FS获取/加载此图像时(另一个进程需要相同的图像)我在检查FS上是否存在图像以及它是否可读时遇到问题:

if ([[NSFileManager defaultManager] fileExistsAtPath:path] && [[NSFileManager defaultManager] isReadableFileAtPath:path]) {
    //step 1 - image exists and I can load it from FS
    UIImage *existingImage = [UIImage imageWithData:[NSData dataWithContentsOfFile:path]];
    if (existingImage == nil) {
        NSLog(@"Loaded image is nil!");
    }
}
else {
    //step 2 - image does not exist in local FS and needs to be loaded from network
}

问题在于,有时我会进入第1步(文件显然存在并且可读)但是加载了#34; existingImage"是零。

怎么会发生这种情况? 图像是否可能处于写入过程的中间? 有没有其他方法可以检查图像写入是否100%完成并准备好使用?

0 个答案:

没有答案