开发者

Saving core data in a thread, how to ensure its done writing before quitting?

开发者 https://www.devze.com 2022-12-26 15:44 出处:网络
So I\'m saving small images to core data which take a really short amount of time to save, like .2 seconds but I\'m doing it while the user is flipping through a scroll view so in order to improve res

So I'm saving small images to core data which take a really short amount of time to save, like .2 seconds but I'm doing it while the user is flipping through a scroll view so in order to improve responsiveness I'm moving the saving to a thread. This works great, everything gets saved and the app is responsive. However, there is one thing in the core-data + multithreading doco that worries me:

"In Cocoa, only the main thread is not-detached. If you need to save on other threads, you must write additional code such that the main thread prevents the application from quitting until all the save operation i开发者_开发百科s complete."

Ok, how do you do that? It only needs to last ~ .2 seconds and its rarely going to happen since the chance of the app quitting as something is saving is very low. How do I run something on the main thread that'll prevent the app from quitting AND not block the gui?

Thanks


Make your save thread set a "save in progress" flag, and have the main thread check that in the app delegate's applicationWillTerminate: method. Obviously, you need to use a mutex to synchronize access to the flag between the two threads.

If a save is in progress when the application is trying to exit, the main thread does a pthread_cond_wait; the save thread will wake it up with pthread_cond_signal once the save completes.

0

精彩评论

暂无评论...
验证码 换一张
取 消