Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot form weak reference to instance of class NSTextView

Tags:

swift

Using Swift only, here's my code in AppDelegate.swift:

import Cocoa

class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet var window: NSWindow
    @IBOutlet var textField: NSTextView

    @IBAction func displaySomeText(AnyObject) {
        textField.insertText("A string...")
    }

    func applicationDidFinishLaunching(aNotification: NSNotification?) {
        // Insert code here to initialize your application
    }

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


}

In the interface builder, I have an object hooked up to receive input from a button, then the output goes to a text view. I'm trying to get the text view to populate with some text when I hit the button.

I tried this with a text field as well, and didn't get the error, but got a "dong" error sound and it didn't do anything else. In Objective-C, you had to use the (assign) parameter to get this to work from what I understand.

What am I doing wrong?

like image 329
Steve Avatar asked Jun 05 '14 14:06

Steve


2 Answers

You cannot store a weak reference to an NSTextView due to historical issues with Cocoa and AppKit. See details in the Clang documentation. NSTextView is marked as NS_AUTOMATED_REFCOUNT_WEAK_UNAVAILABLE in NSTextView.h, there are also a few other classes to lookout.

Have you tried a Swift unowned reference instead of weak, which is kind of like Objective-C's assign (what you'd use for an NSTextView outlet in Objective-C)?

like image 168
Joel Avatar answered Sep 27 '22 22:09

Joel


Use @IBOutlet var scrollView: NSScrollView instead of @IBOutlet var textField: NSTextView.
Then create a property returns documentView in scrollView.

import Cocoa

class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet var window: NSWindow
    @IBOutlet var scrollView: NSScrollView

    var textField: NSTextView {
        get {
            return scrollView.contentView.documentView as NSTextView
        }
    }

    @IBAction func displaySomeText(AnyObject) {
        textField.insertText("A string...")
    }

    func applicationDidFinishLaunching(aNotification: NSNotification?) {
        // Insert code here to initialize your application
    }

    func applicationWillTerminate(aNotification: NSNotification?) {
        // Insert code here to tear down your application
    }
}
like image 34
taggon Avatar answered Sep 27 '22 21:09

taggon