NSData writeToFile not completely written when reading

馋奶兔 提交于 2020-01-02 13:13:35

问题


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.


回答1:


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.




回答2:


The standard solution for a process not finishing in time for the UI is to break it out into a new thread. Maybe you should create a separate thread to save the image and then notify the UI via a delegate method to update itself.



来源:https://stackoverflow.com/questions/11134483/nsdata-writetofile-not-completely-written-when-reading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!