// // ViewController.swift // uiSaveLoadArray // // Created by Michael Wilhelm on 25/04/2016. // Copyright © 2016 Michael Wilhelm. All rights reserved. // import UIKit class ViewController: UIViewController { class Custom:NSObject, NSCoding { var name:String = "" var customno:Int32=0 init(_ name:String, _ customno:Int32) { self.name=name self.customno=customno } override var description:String { return name + ", " + String(customno) } // Protocol NSCoding required init?(coder aDecorder:NSCoder){ name = aDecorder.decodeObjectForKey("name") as! String //customno= aDecorder.decodeObjectForKey("customno") as! Int32 customno= aDecorder.decodeInt32ForKey("customno") } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(name, forKey:"name") aCoder.encodeInt32(customno, forKey: "customno") } } // Custom // save the customs var feld = [Custom]() // uiAttribute @IBOutlet var tErgebnis: UITextView! @IBOutlet var labelTest: UILabel! //uiEvents @IBAction func bnSaveActionClick(sender: UIButton) { saveArray2File() } @IBAction func bnLoadActionClick(sender: UIButton) { loadArrayFromFile() setErgebnisse() } @IBAction func bnInsertActionClick(sender: UIButton) { let n:Int = feld.count let custom= Custom("Pundt" , 12347+n) feld.append(custom) labelTest.text="xx: " + String(feld.count) setErgebnisse() } // save the data with NSKeyedArchiver func setErgebnisse() { var erg:String = "" for customin feld { erg = erg + custom.description + "\n" } tErgebnis.text = "" tErgebnis.text = erg } func saveArray2File() { if feld.count == 0 { return } let filename:String = getPathFilename() if filename.characters.count > 0 { NSKeyedArchiver.archiveRootObject(feld, toFile: filename) } } func loadArrayFromFile(){ let filename:String = getPathFilename() if filename.characters.count > 0 { if let result = NSKeyedUnarchiver.unarchiveObjectWithFile(filename) as? [Custom]{ feld = result } } } private func getPathFilename() -> String { let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) if let path = paths.first { return path+"/custom.bin" } else { return "" } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. var custom= Custom("Meier", 12345) feld.append(custom) custom= Custom("Schmidt", 12347) feld.append(custom) setErgebnisse() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }