首页 > 解决方案 > 如何绕过将“自我”传递给 showWindow 方法?

问题描述

我正在阅读 Big Nerd Ranch 的 Cocoa Programming 第 5 版书中的可可应用程序教程(我在开始的章节中)。在他们讨论这本书的博客网站上,一位用户提到传入“self”不是必需的,第 18 章对此进行了介绍。我现在很好奇如何在不传入的情况下对其进行重构自己'。可能吗?

这段代码基本上是创建一个需要从 AppDelegate 加载的自定义 ViewController 的实例。

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    var mainWindowController: MainWindowController?


    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application

        let mainWindowController = MainWindowController()

        //put the window of the window controller on the screen
        mainWindowController.showWindow(self)

        //set the property to point to the window controller
        self.mainWindowController = mainWindowController
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }
}

如果您需要查看功能,请使用 MainWindowController 类。这是非常基本的,它没有做太多:

import Cocoa

class MainWindowController: NSWindowController {

    @IBOutlet weak var textField: NSTextField!

    override var windowNibName: NSNib.Name {
        return NSNib.Name.init("MainWindowController")
    }

    override func windowDidLoad() {
        super.windowDidLoad()

        // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
    }


    @IBAction func generatePassword(_ sender: AnyObject) {

        //Get a random string of length 8
        let length = 8

        let password = generateRandomString(length: length)

        //tell the text field to display the string
        textField.stringValue = password

    }


}

标签: swiftcocoanswindowcontroller

解决方案


推荐阅读