My app often crash when draw a view with some plot. To keep interface responsive while I calculate data for plot I use threads.
dispatch_async(dispatch_get_main_queue(), ^{
[activity startAnimating];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, NULL), ^{
// do a lot of calculation
[GraphView calculateViewData];
dispatch_async(dispatch_get_main_queue(), ^{
// draw plot
[GraphView setNeedsDisplay];
[activity stopAnimating];
});
});
});
in calculateViewData I fill some arrays which will use later in drawRect. When user click on interface buttons that run code above too fast my app crashes. As I understand while app draw plot in main thread calculateViewData changes arrays in another thread. As result I always crash on this error [__NSArrayI objectAtIndex:] in drawRect
What can I do to fix it? Is copying objects can help in this case?
You can’t manipulate data on one thread and then attempt to utilize that changing data on another. Instead, you do all your manipulations on a background thread and then notify the frontmost/main thread when the manipualtions complete.
Based on your previous questions, you are using Core Data so I recommend reading up on Concurrency in Core Data.
Background processing lets the UI remain responsive but that doesn’t mean you are actually doing two things at once. You have to let data processing finish before you use the data regardless of what thread the processing takes place on.