Demo entry 5994560



Submitted by pdf on Sep 14, 2016 at 05:46
Language: Swift. Code size: 1.7 kB.

import UIKit

// MARK: Database
var dataObj = DataObj(myString: "hello world")

var fileFolder: String {
    let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
    return DocumentsDirectory.URLByAppendingPathComponent("myFileFolder").path!}

class MyViewController: UIViewController {
    @IBOutlet weak var theTextField: UITextField!
    // MARK: Functions
    @IBAction func saveButtonPressed(sender: UIButton) {
        dataObj.myString = theTextField.text!
        _ = NSKeyedArchiver.archiveRootObject(dataObj, toFile: fileFolder)}
    @IBAction func loadButtonPressed(sender: UIButton) {
        dataObj = (NSKeyedUnarchiver.unarchiveObjectWithFile(fileFolder) as? DataObj)!
        theTextField.text = dataObj.myString}
    // MARK: viewDidLoad
    override func viewDidLoad() {
}//End of ViewController Class

class DataObj: NSObject, NSCoding {
    // MARK: Properties
    var myString: String
    // MARK: Key for Encoding and Decoding
    struct Key {
        static let myStringKey = "myStringKey"}
    // MARK: NSCoding Encoding
    @objc func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(self.myString, forKey: Key.myStringKey)}
    // MARK: NSCoding Decoding
    @objc required convenience init?(coder aDecoder: NSCoder) {
        let myString  = aDecoder.decodeObjectForKey(Key.myStringKey) as! String
        self.init(myString: myString)}
    // MARK: Initialization
    init(myString: String) {
        self.myString  = myString
} //End of DataObj Class

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).