Swift / IOS8错误:“致命错误:无法解包Optional.None”

我知道这已经有几个问题,但我无法弄清楚.之前解决的问题表明’profileViewController’是零,但我不知道为什么会这样.用户界面完全是程序化的,没有IB.获得:

“fatal error: Can’t unwrap Optional.None”

在pushViewController()中的代码如下:

class FavoritesViewController: UIViewController {

    init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        // Custom initialization
        self.title = "Favorites"
        self.tabBarItem.image = UIImage(named: "MikeIcon")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.view.backgroundColor = UIColor.redColor()

        let profileButton = UIButton.buttonWithType(.System) as UIButton
        profileButton.frame = CGRectMake(60, 300, 200, 44)
        profileButton.setTitle("View Profile", forState: UIControlState.Normal)
        profileButton.addTarget(self, action: "showProfile:", forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(profileButton)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func showProfile(sender: UIButton) {
        let profileViewController = ProfileViewController(nibName: nil, bundle: nil)
        self.navigationController.pushViewController(profileViewController, animated: true)

    }

这是AppDelegate.swift的相关部分:

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
        // Override point for customization after application launch.

        let feedViewController = FeedViewController(nibName: nil, bundle: nil)
        let favoritesViewController = FavoritesViewController(nibName: nil, bundle: nil)
        let profileViewController = ProfileViewController(nibName: nil, bundle: nil)

        let tabBarController = UITabBarController()
        self.window!.rootViewController = tabBarController

        tabBarController.viewControllers = [feedViewController, favoritesViewController, profileViewController]        


        self.window!.backgroundColor = UIColor.whiteColor()
        self.window!.makeKeyAndVisible()
        return true
    }

最佳答案 导航控制器对象是self.navigationController nil?

navigationController属性上的变量类型是一个未包装的可选项.如果您的View Controller不在UINavigationController中,那将是问题所在.

为了防止崩溃代码沿着以下行写入:

if (self.navigationController)
{
    self.navigationController.pushViewController(profileViewController, animated: true) 
}

或者,您可以将代码编写为:

self.navigationController?.pushViewController(profileViewController, animated: true)

的?如果self.navigationController的计算结果为nil,则运算符将阻止执行任何进一步的代码.

点赞