Coredata is the core framework related to databases in iOS development, but it is a little troublesome in the case of multi-threaded processing. There are three official methods
1. Each thread has an nsmanageobjectcontext
2. There is only one nsmanageobjectcontext, but data is merged by one thread.
3. There is only one nsmanageobjectcontext, but you have to lock the method to achieve thread synchronization.
These three methods are described in the network documentation.
Today, I will introduce a method and present it with a demo. The design philosophy is:
A dedicated thread is used to process all database operations, and a buffer zone is used to store all database operations commands (update/insert/delete/retrive ), I call this thread a database operation thread. If retrive data is required for other threads, such as the main thread, database operation commands are generated and stored in the buffer zone of the database operation thread. Then the database operation thread reads the command execution in the buffer and executes the callback method passed in by the main thread. In fact, this is the producer and consumer model. I use nsconditionlock to synchronize the buffer and use block to implement callback.
Benefits of this design:
1. You only need to implement the callback method and generate the corresponding database operation commands. As for how to write, I have examples in my demo.
2. There is no need to manage the trouble of multi-threaded database operations.
3. Easy to use.
Download the complete Demo: Click to open the link
You can ask me if the Code does not write comments.