简体   繁体   中英

Swift : fatal error: unexpectedly found nil and EXC_BAD_INSTRUCTION

I m new to Xcode and im building a project with a login button. After clicking the login with details in the text field, it will redirect to the second view which is the scroll view controller. However, i got two parts of "Error" 是的

Normally, it work with a normal view controller(login and move to the second view). I have just recreate a view controller to a scroll view controller and it did not work.

By the way, I got a build success but i just got error when i try to "login"

Can anyone explain why i got the thread error and the fatal error? How can i resolve the problem?

login view Controller

 @IBAction func LoginBtn(sender: AnyObject) {
     LoginIn()
 }

 func LoginIn(){
    let user = PFUser()
    user.username = usernameTF.text!
    user.password = passwordTF.text!

    PFUser.logInWithUsernameInBackground(usernameTF.text!,
    password:passwordTF.text! , block: { (User: PFUser?,  Error 
    :NSError? ) -> Void in

        if Error == nil{
            dispatch_async(dispatch_get_main_queue()){

                let Storyboard = UIStoryboard(name: "Main", bundle: nil)
                let MainVC : UIViewController = Storyboard.instantiateViewControllerWithIdentifier("scrollV") as UIViewController

                self.presentViewController(MainVC, animated: true, completion: nil)

            }
        }
        else{
            NSLog("Wrong!!!!")
        }
    })
}

Scroll View Controller

import UIKit

class ScrollViewController: UIViewController {


@IBOutlet weak var scrollView: UIScrollView!

override func viewDidLoad() {
    super.viewDidLoad()


    let V1 : ScrollViewController = ScrollViewController(nibName: "ScrollViewController", bundle: nil)
    self.addChildViewController(V1)
    self.scrollView!.addSubview(V1.view!)
    V1.didMoveToParentViewController(self)
}

You are doing some forced unwrapping, which is not recommended (in general forced stuff in Swift is not recommended), and it will crash your application if the variable being unwrapped is nil . That's why forced unwrap is recommended only when you're 100% sure that you have a valid value in your optional.

In your case, it seems that V1.view! causes the crash, and this might be caused by the fact that V1 didn't successfully loaded from the nib.

Swift has made it very easy to work with nullable values. Just don't force unwrap and use optional binding instead.

@Cristik is correct. Instead of force unwrapping the variable, you should check to see if it is instantiated using the "if let" statement:

if let scrollView = self.scrollView {
     if let subView = V1.view {
          scrollView.addSubview(subView)
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM