0

In my app I'm calling a web service after every 3 seconds on background thread using dispath_async and save the response in coredata after that fetch records from coredatda and display on the UI.My code is

 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{


        [[WebService webServicesManager]getDataWithPath:str ResponseBlock:^(NSString* response, NSString* error)
         {
             if (response != nil) {

                 // save records in core data
                     }
                     dispatch_async(dispatch_get_main_queue(), ^(void) {

                         //Code here is run on the main thread
                       [self showNewRecordsFromDB];


                     });
                 }
             }

        }];

    });

Code above run fine for some time, but after some time(~ 4-5 minutes) i'm getting same data multiple times i.e. same record is showing on screen multiple times.

Is is thread safety problem or any other mistake in my code? please assist me to overcome from this problem.

Edit - I replaced the concurrent queue with serial queue-

dispatch_queue_t = dispatch_queue_create("Messgae Queue",NULL);
dispatch_async(queue, ^{

 //rest code same as above

    });

and i'm getting no issue. Is it ok or i still have to use different context for different thread?

Bharat
  • 2,987
  • 2
  • 32
  • 48
  • 2
    Core data is not thread safe, and your code talks to core data on two different threads. That's madness. – matt Jun 10 '15 at 05:21
  • so please can you tell me how to solve this? – Bharat Jun 10 '15 at 05:27
  • http://stackoverflow.com/questions/7540801/core-data-and-threads-grand-central-dispatch?rq=1 – matt Jun 10 '15 at 05:43
  • Serial queue = data locking, so you have now guaranteed that you are not talking to core data on two threads at the same time. That's good! (But Core Data is still not thread safe, so I do not know whether this is guaranteed to be safe. Let's wait for someone who knows more than I do about Core Data threading to answer...) – matt Jun 10 '15 at 13:06
  • Thanks for the info.. i'v implemented it by serial queue and till now my testing team is happy with that :P – Bharat Jun 10 '15 at 13:13

0 Answers0