问题
I'm a complete beginner to Swift, so this may be a silly question, but I can't figure out how this works...
I have a view with a button inside which calls the following code:
let window = NSWindow()
window.center()
window.title = "test"
window.makeKeyAndOrderFront(self)
When I click the button the window opens just for a moment and disappears a few milliseconds later.
Can anyone help me with that? It seems I have a quite serious misunderstanding about views in Cocoa ;-)
Thanks Tom
回答1:
The problem is that you are creating and 'storing' the NSWindow
in your button action function. That means that as soon as that button action is done, the NSWindow
will go out of context, and be released and thus disappear.
This is how the memory management in Swift works: as soon as nobody owns an object anymore, it will be released.
What you should do is put your window in an instance variable. Like for example:
class YourViewController: NSViewController {
private var window: NSWindow!
@IBAction func buttonAction(sender: UIButton) {
window = NSWindow()
window.center()
window.title = "test"
window.makeKeyAndOrderFront(self)
}
}
The hint about makeKeyAndOrderFront(nil)
makes no difference. Passing either nil
or self
is fine. But latter, how you did it originaly, makes more sense.
来源:https://stackoverflow.com/questions/29399693/swift-nswindow-shows-up-and-disappears-immediately