@IBAction func loginTapped(sender: AnyObject) { let username = usernameField.text let password = passwordField.text if username.isEmpty || password.isEmpty { var emptyFieldsError:UIAlertView = UIAlertView(title: "Please try again",message: "Please fill in all the fields we can get you logged in to your account.",delegate: self,cancelButtonTitle: "Try again") emptyFieldsError.show() } PFUser.logInWithUsernameInBackground(username,password:password) { (user: PFUser?,error: NSError?) -> Void in if user != nil { self.performSegueWithIdentifier("Klikur",sender: self) } else { if let errorString = error!.userInfo?["error"] as? String { self.errorMessage = errorString } self.alertView("Please try again",message: "The username password combiation you have given us does not match our records,please try again.",buttonName: "Try again") } } }
我将故事板ID设置为“测试”,并且当输入正确的信息时它不是切换视图控制器。有人可以帮我解决我的问题吗?
解决方法
至少有一个问题是:
self.performSegueWithIdentifier("Test",sender: self)
应该:
dispatch_async(dispatch_get_main_queue()) { [unowned self] in self.performSegueWithIdentifier("Test",sender: self) }
记住,所有UI操作必须在主线程的队列上执行。你可以通过检查来证明自己是错误的线程:
NSThread.isMainThread() // is going to be false in the PF completion handler
附录
如果没有任何机会,自己可能会变得没有,例如由于不需要而被解雇或以其他方式解除配置,那么您应该以弱的身份捕获自我,而不是无人知晓,并且使用安全的解开方式:如果让s = self {s.doStuff() }或可选链接:self?.doStuff(…)
附录2
这似乎是一个受欢迎的答案,所以在这里提到这个更新的选择很重要:
NSOperationQueue.mainQueue().addOperationWithBlock { [weak self] in self?.performSegueWithIdentifier("Test",sender: self) }
注意,从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.
附录3
苹果在这里隐藏单线规则:
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.
参考:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIKit_Framework/