简体   繁体   中英

How do I save a NSTextField content in macOS Swift?

OK, so I'm working on this OS X application in Swift with Xcode 7 and I can't figure out how to save a string. I want to save a string, so if I write I something in a text field in my application, it will save that string and if I close my application and reopen it that string will still exist and will contain everything that it had before I closed my application.

I hope I make sense.

You can use NSUseDefaults to make your field persist through launches. Just ctrl-click your text field and add a IBAction to it that will be called when the user ends editing the text field. Just save the text field (sender) stringValue there, connect one IBOutlet also to your text field and use NSUserDefaults stringForKey method to load your string back inside viewDidLoad method:

import Cocoa

class ViewController: NSViewController {
    @IBOutlet var textField: NSTextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        textField.stringValue = NSUserDefaults().stringForKey("textFieldKey") ?? "default value"
    }
    override var representedObject: AnyObject? {
        didSet {
        }
    }
    @IBAction func textFieldAction(sender: NSTextField) {
        NSUserDefaults().setObject(sender.stringValue, forKey: "textFieldKey")
    }
}

If you just want to save simple data, such as a few strings, you can use NSUserDefaults. Check out a tutorial here .

If you want to save complicated data, you should use Core Data. It seems harder to learn at the beginning but you will enjoy its convenience and performance later. I learned Core Data here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM