通用文件存储
1 import UIKit 2 3 class ViewController: UIViewController { 4 5 @IBOutlet weak var textField: UITextField! 6 7 @IBAction func btnSave(sender: UIButton) { 8 var text = textField.text as NSString 9 10 //写入文件(可序列化) 11 text.writeToFile(getPath("data.txt"), atomically: false, encoding: NSUTF8StringEncoding, error: nil) 12 13 } 14 15 @IBAction func btnLoad(sender: UIButton) { 16 // 获取一个TXT的文件目录 17 var txtFilepath = getPath("data.txt")//字符串数据 18 if NSFileManager.defaultManager().fileExistsAtPath(txtFilepath) { 19 var text = NSString(contentsOfFile: txtFilepath, encoding: NSUTF8StringEncoding, error: nil) 20 textField.text = text as! String 21 } 22 23 } 24 25 override func viewDidLoad() { 26 super.viewDidLoad() 27 /** 28 通用文件存储可以进行序列化的类(字典和数组) 29 NSData 30 NSString(String) 31 NSNumber(Int, Double, Float) 32 NSDate 33 NSArray(Array) 34 NSDictionary 35 */ 36 /** 自己创建的对象不能 37 没有在前面可序列化对象的其他类不能(UIColor,UIImage) 38 不能在自身里面 39 大数据一半不用 40 */ 41 42 43 } 44 45 override func didReceiveMemoryWarning() { 46 super.didReceiveMemoryWarning() 47 // Dispose of any resources that can be recreated. 48 } 49 //获取文件目录 50 func getPath(fileName:String)->String { 51 var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) 52 var documents = paths[0] as? String 53 return documents!.stringByAppendingPathComponent(fileName) 54 } 55 56 }
时间: 2024-10-12 18:36:03