grabury
grabury

Reputation: 5559

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?

Upvotes: 13

Views: 4242

Answers (1)

DarkDust
DarkDust

Reputation: 92335

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.

Upvotes: 20

Related Questions