imacswift’s blog

There is no article rambling

XCode Version 9.1 (9B55)のSwiftでmacosアプリ開発時、紫色でNSControl.stringValue must be used from main thread onlyを表示する場合

<事象>
macosでテキストフィールドへ文字を代入する場合、
紫色でNSControl.stringValue must be used from main thread onlyを表示して動かない。

<解決方法>
 メインスレッドで実行するため、Notificationとスレッド処理を使う。

1.Notificationを定義

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(self.doSomething(_:)),
            name: NSNotification.Name("NotificationKey"),
            object: nil
        )
    }

2.呼び出し先を定義

     @objc func doSomething(_ notification: Notification) {
            txtOutput.stringValue =  “更新!”
    }

3.呼び出し

    func yobidasimoto() {     
        self.updateViewConstraints()
         DispatchQueue.main.async {
	        NotificationCenter.default.post(
	        name: NSNotification.Name("NotificationKey"),
	        object: nil)
        }
    }

(1〜3はすべてclass ViewController: NSViewController 内に記述しています。)

Takahiro Octopress Blog
http://grandbig.github.io/blog/2017/02/12/notification-and-thread/
を参考にさせていただきました。ありがとうございます。