Swift performSegueWithIdentifier not working

后端 未结 8 1514
礼貌的吻别
礼貌的吻别 2020-12-01 04:13

I am trying to switch view controllers after a user successfully logs in to their account, but it is not working correctly. I cant use a segue directly because if the login

8条回答
  •  一整个雨季
    2020-12-01 04:44

    [Assuming that your code is not crashing, but rather just failing to segue]

    At least one problem is:

    self.performSegueWithIdentifier("Test", sender: self)
    

    should be:

    dispatch_async(dispatch_get_main_queue()) {
        [unowned self] in
        self.performSegueWithIdentifier("Test", sender: self)
    }
    

    Remember that all UI operations must be performed on the main thread's queue. You can prove to yourself you're on the wrong thread by checking:

    NSThread.isMainThread() // is going to be false in the PF completion handler
    

    ADDENDUM

    If there's any chance self might become nil, such as getting dismissed or otherwise deallocated because it's not needed, you should capture self weakly as [weak self] not unowned, and use safe unwrapping: if let s = self { s.doStuff() } or optional chaining: self?.doStuff(...)

    ADDENDUM 2

    This seems to be a popular answer so it's important to mention this newer alternative here:

    NSOperationQueue.mainQueue().addOperationWithBlock {
         [weak self] in
         self?.performSegueWithIdentifier("Test", sender: self)
    }
    

    Note, from https://www.raywenderlich.com/76341/use-nsoperation-nsoperationqueue-swift:

    NSOperation vs. Grand Central Dispatch (GCD)

    GCD [dispatch_* calls] is a lightweight way to represent units of work that are going to be executed concurrently.

    NSOperation adds a little extra overhead compared to GCD, but you can add dependency among various operations and re-use, cancel or suspend them.

    ADDENDUM 3

    Apple hides the single-threaded rule here:

    NOTE

    For the most part, use UIKit classes only from your app’s main thread. This is particularly true for classes derived from UIResponder or that involve manipulating your app’s user interface in any way.

    SWIFT 4

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

    Reference:

    https://developer.apple.com/documentation/uikit

提交回复
热议问题