Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to perform a segue off the main thread?

Is it ok to perform a segue off the main thread?

user.saveInBackgroundWithBlock { (success: Bool!, error: NSError!) -> Void in
 if success == false || error != nil {
  println(error)
 } else {
  self.performSegueWithIdentifier("jumpToMessagesViewController", sender: self)
 }
}

Or what is the correct way to do this?

like image 556
grabury Avatar asked Jan 04 '15 13:01

grabury


1 Answers

Generally, all Cocoa and Cocoa Touch operations should be done on the main thread. If you don't you may experience problems like UI not updating properly and sometimes even crashes. So you should wrap your call to performSegueWithIdentifier:

DispatchQueue.main.async {
  self.performSegue(withIdentifier: "jumpToMessagesViewController", sender: self)
}

In UIKit (Cocoa Touch), calling UI stuff on a background thread was a sure way to crash in the olden days. Since iOS 4 (IIRC) a lot of things are now "thread-safe" in the sense that the app doesn't crash any more but some operations simply get ignored when executed in a background thread. So it's always a good idea to execute your code that messes with UI objects on the main thread.

I'm not sure about the thread-safety of AppKit (Cocoa). I know that calling AppKit stuff on background threads could crash your app but I don't know whether that's true any more. Better be safe than sorry and call your UI objects on the main thread as well.

like image 109
DarkDust Avatar answered Sep 19 '22 22:09

DarkDust