Reputation: 312
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.
Upvotes: 1
Views: 823
Reputation: 236360
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")
}
}
Upvotes: 2
Reputation: 6570
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.
Upvotes: 1