ios - Why are UI events not thread-safe in Swift/Objective-C? -


so i'm beginning learn basics of grand central dispatch , whole concept of multithreading ios applications. every tutorial tell you must run ui events on main thread, don't understand why.

here's problem came across yesterday, , fixed running segue on main thread, still don't understand why running off main thread problem:

i had custom initial vc (barcode scanner) , segue new view controller uiwebview attached. vc found barcode, called handler, , in closure, had performseguewithidentifier. however, got exc_bad_access because of (it didn't happen when second vc had label or uiimageview, uiwebview). realized reason, closure called off main thread, , segue being performed off main thread. why performing segue on thread throw memory error? because self in self.performseguewithidentifier somehow nil? , why wouldn't swift automatically dispatch segue event on main thread?

interesting question! crash isn't related uikit. it's crash specific uiwebview. looking @ stack trace, exception happens in webcore::floatingpointenvironment::savemainthreadenvironment function, part of webkit init process. since webkit manages threaded execution environment of own, makes sense needs definite starting point (i.e. main thread) build environment.

uikit operations (like presenting view controller) performed on threads other main not cause exception, delayed (depending on qos of dispatching queue).

as why uikit operations aren't automatically dispatched on main queue, can speculate adding checks inside library calls add redundant work can avoided following convention.

for larger discussion on uikit , main thread, see answer: why must uikit operations performed on main thread?

the short answer operations modify ui of app need come in 1 place evaluated generate next frame @ regular intervals (the v-sync interval specifically). keeping track of of mutated state requires changes happen synchronously, , performance reasons, of these operations batched , executed once per frame (while coordinating gpu).


Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -