NSData writeToFile在读取时未完全写入 [英] NSData writeToFile not completely written when reading

查看:285
本文介绍了NSData writeToFile在读取时未完全写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在撰写一个iPhone应用程式,可让您在一个资料检视中浏览图片,并在另一个资料页中建立。



使用以下代码(当点击按钮以关闭视图时)到文档文件夹:

  [UIImagePNGRepresentation(image)writeToFile: path atomically:YES]; 

浏览器视图将使用以下命令加载图片:

  UIImage * image = [UIImage imageWithContentsOfFile:path]; 

现在这个工作完美9次10次。 1 out of 10图像不完全写入之前,我加载它所以下半部分将是黑色的。一切都将最终写入 - 如果我在浏览器中重新加载图像,将显示完整的图像。



我可以做些什么来防止这种行为吗?



现在我正在考虑将新创建的图像传回浏览器,但这只是一个黑客,因为浏览器显示所有以前创建的图像。

如果您确定该图像正以 writeToFile:atomically:保存在主(UI)线程上,该图像然后也被加载在主线程上,则看起来像该方法的问题,保持其契约以在调用返回时完成操作。 iOS有时会有错误,也许你找到了一个。



然而,我也注意到,一个可能的方式,我看到类似的问题出现是假设是关于订单,其中 viewWillAppear viewDidDisappear 等在一个视图显示另一个视图时调用。所以,我还要确保图像不保存在这些方法之一。



因为你说的问题显示一个图像是可见,我想这不是这样,但我包括任何人有类似的操作顺序问题的警告。


I am writing an iPhone app that allows you to browse images in one view, and create them in another.

The view that creates an image will write the image to the documents folder using the following code (when tapping a button to dismiss the view):

[UIImagePNGRepresentation(image) writeToFile:path atomically:YES];

The browser view will load the image using:

UIImage *image = [UIImage imageWithContentsOfFile:path];

Now this works perfectly 9 out of 10 times. 1 out of 10 the image is not completely written before I load it so the lower half of it will be black. Everything will be written eventually - if I reload the image in the browser, the full image is shown. I thought that these things would always be consistent within a single thread.

Can I do something to prevent this behavior?

Right now I'm thinking about passing the newly created image back to the browser but that just seems like a hack since the browser shows all your previously created images as well.

解决方案

If you are sure that the image is being saved on the main (UI) thread with writeToFile:atomically:, and the image is then being loaded also on the main thread, then it looks like there's a problem with that method maintaining its contract to complete the operation by the time the call returns. iOS does sometimes have bugs, and maybe you found one.

I will also note, however, that one possible way that I've seen similar problems arise is when assumptions are made about the order in which viewWillAppear, viewDidDisappear, etc. are called when leaving one view to display another. So, I'd also make sure the image isn't saved in one of these methods.

Since you said the problem shows an image that is half visible, I would guess that this is not the case, but I include the warning for anyone else with a similar problem with order-of-operations.

这篇关于NSData writeToFile在读取时未完全写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆