引用IBOutlets时为Nil值 - swift,Cocoa [英] Nil value when referring to IBOutlets - swift, Cocoa

查看:170
本文介绍了引用IBOutlets时为Nil值 - swift,Cocoa的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我的NSTextField IBOutlets显示为零,即使他们连接到故事板。在下面的简化示例中,我有一个按钮,当按下时,应该列出3个文本标签的字符串值。

I am having an issue where my NSTextField IBOutlets are showing up as nil, even though they are connected to the storyboard. In the simplified example below, I have a button that, when pressed, should list the string value of the 3 text labels.

以下是按钮的代码:

import Foundation
import Cocoa

class ViewController: NSObject{

    @IBAction func pushButton(sender: AnyObject) {
        let oneText = Texts()
        oneText.listTextFields()
    }

}

NSTextField列表的代码:

Here is the code for the NSTextField list:

import Foundation
import Cocoa

class Texts: NSObject{

    @IBOutlet weak var l1: NSTextField!
    @IBOutlet weak var l2: NSTextField!

    @IBOutlet weak var l3: NSTextField!

    var textArray = [NSTextField]()

    func listTextFields (){
      self.textArray = [self.l1,self.l2,self.l3]

        for var i = 0; i < textArray.count; i++ {
            let text = textArray[i]
            print(text.stringValue)
        }
    }
}

我已经验证IBOutlets都已连接,但是当我运行程序时,我收到一个致命错误:意外发现nil当解包可选值并按下按钮。看看调试器,看起来树NSTextfields是nil。

I have verified that the IBOutlets are all connected, but I get a "fatal error: unexpectedly found nil while unwrapping an Optional value" message when I run the program and press the button. Looking at the debugger, it appears that the tree NSTextfields are "nil."

我做错了什么?

推荐答案

从你的故事板中加载文本,所以它不知道你的插座。 Texts()创建一个对象的新实例,然后您可以调用该方法。

You're not loading Texts from your storyboard, so it knows nothing about your outlets. Texts() creates a new instance of the object, which you then call the method on.

您可能在界面构建器 ViewController 中有某个现有 Texts c $ c>应该有一个出口。

You presumably have an existing Texts object somewhere in interface builder, ViewController should have an outlet to that.

这篇关于引用IBOutlets时为Nil值 - swift,Cocoa的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆