D
D
Damir2015-05-10 17:45:51
Swift
Damir, 2015-05-10 17:45:51

How to redraw View from another thread?

Good day to all!
Such a task. There is a collection of objects of the View type, whose drawRect method has been rewritten. In the main thread, a secondary thread is created with an infinite loop, in which a certain method is called for each view, at the end of which the view should be redrawn.

func StartStopTapped(){
   let backgroundQueue: dispatch_queue_t = dispatch_queue_create("SecondThread", DISPATCH_QUEUE_CONCURRENT)
   dispatch_async(backgroundQueue) {
      while self.started{
         for figure in FiguresManager.sharedInstance.figures{
            figure.1.calculateNextIterate()
         }
         usleep(40000)
      }
   }
}
.
.
.
метод в классе Figure

func calculateNextIterate(){
   dispatch_sync(dispatch_get_main_queue(), {
      self.setNeedsDisplay()
   })
}

Like this, I'm trying to do it. But the shapes are not redrawn even though the drawRect method is called and the display options are changed. I would be very grateful for help. Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Damir, 2015-05-12
@YaMirok

In general, the following happened. I replaced
dispatch_sync(dispatch_get_main_queue()
with
dispatch_ a sync(dispatch_get_main_queue() )
and it seemed to work. But there is a possibility that it worked before, just the size change was insignificant = 0.32 points, which is imperceptible to the eye.

A
An, 2015-05-10
@Flanker_4

While not everything is clear. A big request, give an example project with a problem
PS A small recommendation, that's usleep(40000) is not very cool. Better start a timer on the GCD
Here with a link to the office. dock

dispatch_source_t CreateDispatchTimer(uint64_t interval, uint64_t leeway, dispatch_queue_t queue, dispatch_block_t block)
{
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    if (timer)
    {
        dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), interval, leeway);
        dispatch_source_set_event_handler(timer, block);
        dispatch_resume(timer);
    }
    return timer;
}

Use (only replace queue with yours)
dispatch_source_t newTimer = CreateDispatchTimer(1ull * NSEC_PER_SEC, (1ull * NSEC_PER_SEC) / 10, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // Repeating task
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question