The use of multithreading in core data

Source: Internet
Author: User

We know that Core data is thread insecure. We cannot share the same nsmanagedobject and Nsmanagedobjectcontext objects in different threads. The creation and use of Nsmanagedobjectcontext objects must be in the same thread.


When we use Nsoperation to implement multithreaded operations on core data, it is important to note that the Init method of Nsoperation is executed on the calling thread, and that the start and main methods are executed in nsoperation threads. Therefore, to create a nsmanagedobjectcontext in a child thread, it must be executed in the start or Main method, or there will be a thread safety issue.


Official documents

You must create the managed context on the thread on which it'll be used. If You use nsoperation, note the IT init method is invoked on the same thread as the caller. You must no, create a managed object context for the queue in the queue ' s Init method, otherwise it si associated with th E caller ' s thread. Instead, you should create the context in main (for a serial queue) or start (for a concurrent queue).


Using thread confinement, you should not pass managed objects or managed object contexts between thread. To ' Pass ' a managed object from one context another thread boundaries, you either:


1. Pass its object ID (ObjectID) and use Objectwithid:or ExistingObjectWithID:error:on the receiving managed object Conte Xt.


The corresponding managed objects must has been saved-you cannot pass the ID of a newly-inserted managed object to Anot Her context.


2. Execute a fetch on the receiving context.



Examples are as follows:

The main function for this nsoperation, to start the parsing.

-(void) Main {

// Creating context in main function here make sure the Contex T is tied to

Current thread.

Init:use thread confine model to make things simpler.

Self.managedobjectcontext = [[Nsmanagedobjectcontext alloc] init];

Self.managedObjectContext.persistentStoreCoordinator = SELF.SHAREDPSC;


}


When multi-threading is used in core data, it encounters a context interaction problem in two threads. We use Nsmanagedobjectcontext's notifications to implement different thread interactions.

1, Nsmanagedobjectcontextdidsavenotification


2, Nsmanagedobjectcontextdidchangenotification


For example, there are two threads, a, B. A is a background thread, and B is the main thread.

Method One: Use Contextdidsave notification to interact with the following methods:

In the main thread B register nsmanagedobjectcontextdidsavenotification, in the background thread A for related operations: Add, delete, change, check operation. After the end, the context in the save background thread. Background context will send a notification of save. The main thread will get this notification, due to the need to change and into the main thread of the context, you can call the main thread context of the Mergechangesfromnotification method, after completion of the UI refresh.


It is important to note that because the notification is received in the sending thread of the notification, and the context is thread insecure, it is necessary to dispatch to the main thread after receiving the notification in order to go to the merge changes. Examples are as follows:


Registering notifications in the main thread

Observe the Parseoperation ' s save operation with its managed object context.

[[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (mergechanges:) Name: Nsmanagedobjectcontextdidsavenotification Object:nil];


Process notifications in the main thread

This was called via observing "nsmanagedobjectcontextdidsavenotification" from

Our aplparseoperation

-(void) Mergechanges: (nsnotification *) Notification {

if (notification.object! = Self.managedobjectcontext) {

//Because the notification is executed in a background thread and the context is thread insecure, the Update method needs to be

Dispatch to the main thread.

[Self Performselectoronmainthread: @selector (updatemaincontext:) withobject:notification Waituntildone:no];

}

}


Merge changes to main context, Fetchedrequestcontroller would automatically monitor

The changes and update TableView.

-(void) Updatemaincontext: (nsnotification *) Notification {

ASSERT ([Nsthread ismainthread]);

[Self.managedobjectcontext mergechangesfromcontextdidsavenotification:notification];

}


The following actions are performed by Mergechangesfromcontextdidsavenotification:

/*

Merges the changes specified in notification object received from another context ' s Nsmanagedobjectcontextdidsavenotifica tion into the receiver. This method would refresh any objects which has been updated in the other context, fault in any newly inserted objects, an D invoke deleteobject:on those which have been deleted. The developer is only responsible for the thread safety of the receiver.

*/

-(void) Mergechangesfromcontextdidsavenotification: (nsnotification *) notification;




The use of multithreading in core data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.