无法使用“(String)”类型的参数列表调用 <method>

Cannot invoke <method> with and argument list of type '(String)'

我正在尝试编写 OSX 应用程序。这个应用程序的一个功能是它显示机器 IP 地址。 打开程序时取地址(AppDelegate.swift):

@NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate {

      var ipadd:String = ""
      var path:String = ""
      var status:String = ""


      func applicationDidFinishLaunching(aNotification: NSNotification) {
             ipadd = getIFAddress()  //<-- ip stored in here as String
             println(ipadd)   //successfully prints out the ip
             ViewController.setIpDisp(ipadd)   //error on this line

      }
   ...
 }

在ViewController.swift中:

class ViewController: NSViewController {

    @IBOutlet weak var ip: NSTextField!
    ...

    func setIpDisp(ipin: String){
         ip.stringValue = ipin 
    }

确切地说,错误是“无法使用类型为‘(String)’的参数列表调用 'setIpDisp'

谢谢

您的函数不是静态的,因此请确保初始化它的一个实例,就像这样

    @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate {
      let viewController = ViewController()

      var ipadd:String = ""
      var path:String = ""
      var status:String = ""


      func applicationDidFinishLaunching(aNotification: NSNotification) {
             ipadd = getIFAddress()  //<-- ip stored in here as String
             println(ipadd)   //successfully prints out the ip
             viewController.setIpDisp(ipadd)   //error on this line

      }
   ...
 }

AppDelegate 正在尝试调用 ViewController 方法来更新视图控制器视图中的 @IBOutlet。它需要一个有效的 ViewController 实例才能做到这一点。

但这是倒退的:应用程序委托不应该尝试调用视图控制器方法。视图控制器可以调用应用程序委托的 methods/properties,但应用程序委托实际上不应该调用视图控制器方法。

如果您需要更新视图控制器中的 IP 号码字段,那么视图控制器应该启动此操作(例如在 viewDidLoad 中):

class ViewController: NSViewController {

    @IBOutlet weak var ip: NSTextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        updateIpDisp()
    }

    func updateIpDisp() {
        let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate

        ip.stringValue = appDelegate.getIFAddress()
    }

}

或者,如果您愿意,AppDelegate 在其 init 方法(不是 applicationDidFinishLaunching)中设置一些 ipadd 字符串 属性,然后updateIpDisp() 方法也可以从应用程序委托中检索 属性 的值。 (考虑到 IP 号码是动态的并且可以更改,这对我来说似乎不正确,但是您可以随心所欲。)无论如何,这可能看起来像:

class AppDelegate: NSObject, NSApplicationDelegate {

    var ipadd: String!

    override init() {
        super.init()

        ipadd = getIFAddress()
    }

}

class ViewController: NSViewController {

    @IBOutlet weak var ip: NSTextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        updateIpDisp()
    }

    func updateIpDisp() {
        let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate

        ip.stringValue = appDelegate.ipadd
    }

}

但是视图控制器应该从应用代理请求 IP 号并更新它自己的视图。但是应用程序委托在视图控制器中没有业务调用方法。