ios - Swift - SecondViewController 到 FirstViewController : fatal error: unexpectedly found nil

标签 ios swift

我试图弄清楚如何在 Swift 中解决这个问题,但我也遇到了这个错误:“ fatal error :在展开可选值时意外发现 nil”。任何建议表示赞赏。谢谢。

来自 FirstViewController

    func getDatafromSecondViewController(myMessage: String){

         println(myMessage)

    }

来自 SecondViewController

    func sendThisDataToFirstViewController() {

         let firstViewController = FirstViewController()
         firstViewController.getDatafromSecondViewController("Testing")
    }

注意:我无法使用 prepareForSegue,因为我正在使用这些文件“class FirstViewController: UIViewController”和“class SecondViewController: NSObject”作为示例。

最佳答案

如果我没记错的话,我认为通过使用这些你可以将 myMessage 打印到控制台,但是当你尝试使用变量时,它不起作用。如果是这样,我认为问题如下:

当您执行 let firstViewController = FirstViewController() 时,您正在创建一个类型为 FirstViewController 并命名为 firstViewController 的新 View Controller 。它刚刚创建,因此任何未分配的变量都将为 nil,因此会抛出此错误。您需要对原始 FirstViewController 的引用。您需要一名代表来执行此操作。

以下是实现您想要执行的操作的简单方法。 在你继续之前,在右边的第二个分配你的第一个 View Controller :

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
            if segue.identifier == "yourSegueIdentifierHere" {
                let nextViewController = segue.destinationViewController as SecondViewController
                nextViewController.myVariable = self.variableToPass
            }
}

当然,您需要该变量存在于将出现的 View Controller 中,因此在靠近顶部但在类内部声明它:

var myVariable: YourTypeHere!

关于ios - Swift - SecondViewController 到 FirstViewController : fatal error: unexpectedly found nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28226772/

相关文章:

ios - 在 swift 中使用 objective c 协议(protocol)

html - 如何在 SwiftUI 文本中显示 HTML 或 Markdown?

iphone - numberOfLines=2 的 UILabel 使用什么约束高度? (使用 [NSString sizeWithFont...])

swift - 这是使用 RealmSwift 实现树结构的最 "general"方式吗?

ios - 对 UIViewController 的某些部分启用 UserInteraction

ios - Swift 代码组织方式 : Extensions vs. Classes and Structs

ios - 用 NavigationViewController swift 呈现 ViewController

ios - 如何隐藏 .numberPad 键盘上的字母?

ios - 使用 AudioQueue 在 iOS 上进行失真(机器人)录音

ios - 如果再次点击 TableView 中的单元格,UIAlertController 会给出 sigabrt 错误