lundi 16 mars 2015

Processing data on a secondary thread

Well, I'm using the framework multipeer connectivity to share data between two devices. We know that when the device receive a data with this framework, he calls the method: -(void)session:(MCSession *)session didReceiveData:(NSData *)data fromPeer:(MCPeerID *)peerID.


When I receive a data I save this data inside my database (SQLite) and finally I send a Notification to system claiming that all data has been entered into the database. And another class (UIViewController) execute the command popViewController to dismiss the ViewController connection screen.


So, let's see the code structure:



-(void)session:(MCSession *)session didReceiveData:(NSData *)data fromPeer:(MCPeerID *)peerID{

//... Commands to get the data

[self insertDatas:^(BOOL finished) {
if(finished){
[self addNotification:@"Complete"];
[mySession disconnect];
}
}];

}


But my code has a small problem:



  • Sometimes both the data is saved in the database (in two devices)

  • Sometimes only one device can save the data in the database


And I think I already found the answer to this problem!


What is happening is this: the method -(void)session:(MCSession *)session didReceiveData:(NSData *)data fromPeer:(MCPeerID *)peerID it seems that runs on a secondary thread, in this case all the methods that are being called by this method surely will run also on a secondary thread. Then, the command responsible for entering data into the database is running on a secondary thread, and then I send a notification causing the popViewController of this class.


As a consequence of this, the data were not yet registered in the database will never be registered, since the compiler implemented the code to close the screen, thus making the processes that were still pending in a secondary thread to be deleted.


Knowing this, what is the solution I could find to my problem?


Aucun commentaire:

Enregistrer un commentaire