读写应用程序数据-NSUserDefault、对象归档(NSKeyedArchiver)、文件操作
ios中数据持久化存储方式一般有5种:NSUserDefault、对象归档(NSKeyedArchiver)、文件操作、数据库存储(SQLite3)、CoreData。
1、NSUserDefault用于保存程序相关的偏好设置和配置数据等,以便下次启动程序后能恢复上次的设置。
NSUserDefault和对象归档
1 //通过单利来创建一个NSUserDefaults对象,全局变量NSUserDefault,可在整个项目传递变量 2 let userDefault:NSUserDefaults = NSUserDefaults.standardUserDefaults() 3 4 //通过init方法创建 5 let userDefault1:NSUserDefaults = NSUserDefaults(suiteName: "SwiftClass")! 6 print(userDefault1.dictionaryRepresentation()) 7 8 //获取userDefault单利下所有的值 9 print(userDefault.dictionaryRepresentation()) 10 11 //判断NSUserDefaults的“appMessage”key 在dictionaryRepresentation中是否存在,如果不存在就设置“appMessage”值为This is app message。 12 if(userDefault.objectForKey("message") == nil){ 13 userDefault.setObject("This_is_my_default_message", forKey: "message") 14 } 15 16 //如果想单独看某个key的设置,例如: 17 let dic = userDefault.dictionaryRepresentation() 18 let object_one:AnyObject? = (dic as NSDictionary).objectForKey("AppleKeyboards") 19 // //或者 20 // var object_one:AnyObject? = dic["AppleKeyboards"] 21 22 if let oValue: AnyObject! = object_one { 23 print(oValue) 24 } 25 26 27 //Int类型 28 //设置 29 userDefault.setInteger(123456, forKey: "Int") 30 //读取 31 let intValue = userDefault.integerForKey("Int") 32 print(intValue) 33 34 //Float类型 35 //设置 36 userDefault.setFloat(3.2, forKey: "Float") 37 //读取 38 let floatValue = userDefault.floatForKey("Float") 39 print(floatValue) 40 41 //Double类 42 //设置 43 userDefault.setDouble(5.6890, forKey: "Double") 44 //读取 45 let doubleValue = userDefault.doubleForKey("Double") 46 print(doubleValue) 47 48 //Bool类型 49 //设置 50 userDefault.setBool(true, forKey: "Bool") 51 //读取 52 let boolValue = userDefault.boolForKey("Bool") 53 print(boolValue) 54 55 //NSURL类型 56 //设置 57 userDefault.setURL(NSURL(string: "http://www.iphonetrain.com")!, forKey: "NSURL") 58 //读取 59 let urlValue = userDefault.URLForKey("NSURL") 60 print(urlValue)
1 //保存NSDate数据 2 //将对象转换成NSData流 3 let imageData:NSData = NSKeyedArchiver.archivedDataWithRootObject(UIImage(named: "SwiftClassWeiXin.png")!) 4 5 //存储NSData对象 6 userDefault.setObject(imageData, forKey: "imageData") 7 8 //读取数据 9 //获取NSData 10 let objData:AnyObject? = userDefault.objectForKey("imageData") 11 12 //还原对象-初始一个UIImage对象 13 let myImage:AnyObject? = NSKeyedUnarchiver.unarchiveObjectWithData(objData as! NSData) 14 15 print(myImage)
1 //自定义的类实现存取需要通过NSData做载体 2 3 //创建AppsModel的实例 4 let model = AppsModel(imageName: "appIcon2.png", app_Name: "租房点评", app_Description: "租房被骗?现在开始,你来改变这一切!《租房点评》为你而备,租房无忧!") 5 6 //实例对象转换成NSData 7 let modelData:NSData = NSKeyedArchiver.archivedDataWithRootObject(model) 8 9 //存储NSData对象 10 userDefault.setObject(modelData, forKey: "myAppModel")
1 //保存NSString, 2 userDefault.setValue("1_NSString", forKey: "NSString") 3 userDefault.setObject("1_NSString1", forKey: "NSString1") 4 5 //保存NSNumber, 6 let number:NSNumber = NSNumber(int: 32) 7 userDefault.setValue(number, forKey: "number") 8 userDefault.setObject(number, forKey: "number1") 9 10 //保存NSArray 11 let array1:NSArray = NSArray(array:["22222","33333"]) 12 userDefault.setValue(array1, forKey: "array") 13 userDefault.setObject(array1, forKey: "array1") 14 15 //保存NSDictionary 16 let dictionary:NSDictionary = NSDictionary(dictionary: ["1":"1111"]) 17 userDefault.setValue(dictionary, forKey: "dictionary") 18 userDefault.setObject(dictionary, forKey: "dictionary1")
1 var value:AnyObject? = userDefault.valueForKey("dictionary") 2 print(value) 3 4 value = userDefault.objectForKey("dictionary1") 5 print(value) 6 7 8 9 //-------- 删除所有的值 10 let ar:NSDictionary = userDefault.dictionaryRepresentation() 11 12 for key in ar.allKeys { 13 14 userDefault.removeObjectForKey(key as! String) 15 16 userDefault.synchronize()//内存中数据同步更新数据库 17 }
2、文件操作
应用开发中所有的非代码文件都存储在沙盒中。
1 //1、获取程序的Home目录 2 let homeDirectory = NSHomeDirectory() 3 print(homeDirectory) 4 5 6 //2、获取Documents目录 7 let documentPaths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) 8 9 let documentPath = documentPaths[0] 10 print(documentPath) 11 12 //或通过home目录自己追加文件夹 13 let documentPath2 = homeDirectory + "/Documents" 14 print(documentPath2) 15 16 //3、获取Library目录 17 let libraryPaths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomainMask.UserDomainMask, true) 18 let libraryPath = libraryPaths[0] 19 print(libraryPath) 20 21 //或通过home目录自己追加文件夹 22 let libraryPath2 = homeDirectory + "/Library" 23 print(libraryPath2) 24 25 26 27 28 //4、获取Cache目录 29 let cachesPaths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true) 30 let cachesPath = cachesPaths[0] 31 print(cachesPath) 32 33 //或通过home目录自己追加文件夹 34 let cachesPath2 = homeDirectory + "/Library/Caches" 35 print(cachesPath2) 36 37 38 //5、获取Tmp目录 39 let tmpDir = NSTemporaryDirectory() 40 print(tmpDir) 41 42 //或通过home目录自己追加文件夹 43 let tmpDir2 = homeDirectory + "/tmp" 44 print(tmpDir2)
对文件操作需要先创建一个文件管理器
// 创建文件管理器 let fileManager :NSFileManager = NSFileManager.defaultManager()
1 //创建目录 2 //定义几个自己的目录 3 let myDirectory1:String = NSHomeDirectory() + "/Documents/myFolder/Images" 4 let myDirectory2:String = NSHomeDirectory() + "/Documents/myFolder/Films" 5 let myDirectory3:String = NSHomeDirectory() + "/Documents/myFolder/Musics" 6 let myDirectory4:String = NSHomeDirectory() + "/Documents/myFolder/Files" 7 8 //创建目录 9 //withIntermediateDirectories 设置成true,代表中间所有的路径目录如果不存在,都会创建 10 //如果设置成false,因为myFolder目录不存在,所以无法创建1234目录 11 12 //创建myDirectory1目录 13 do 14 { 15 try fileManager.createDirectoryAtPath(myDirectory1, withIntermediateDirectories: true, attributes: nil) 16 } 17 catch let error as NSError { 18 print(error)//如果创建失败,error 会返回错误信息 19 } 20 21 //创建myDirectory2目录 22 do 23 { 24 try fileManager.createDirectoryAtPath(myDirectory2, withIntermediateDirectories: true, attributes: nil) 25 } 26 catch let error as NSError { 27 print(error)//如果创建失败,error 会返回错误信息 28 } 29 30 //创建myDirectory3目录 31 do 32 { 33 try fileManager.createDirectoryAtPath(myDirectory3, withIntermediateDirectories: true, attributes: nil) 34 } 35 catch let error as NSError { 36 print(error)//如果创建失败,error 会返回错误信息 37 } 38 39 //创建myDirectory4目录 40 do 41 { 42 try fileManager.createDirectoryAtPath(myDirectory4, withIntermediateDirectories: true, attributes: nil) 43 } 44 catch let error as NSError { 45 print(error)//如果创建失败,error 会返回错误信息 46 }
Swift 的错误处理机制要求你必须使用 do-catch 语句来捕获所有的错误并处理他们。
//创建文件 let filePath = myDirectory1 + "/appInfo.txt" let info = "经常听到:被中介骗了,押金不退,晚一天交房租,被讹了。租房普遍现象:网上报价不真实?经常被忽悠!(看房时报价都比网上高!)证件不齐全,被骗过!(其实根本不是房东啦!)看房前态度都很热情! 签约之后态度骤变!入住后家电维修只能靠自己! 房屋到期,押金各种被勒索!现在开始,你来改变这一切!《租房点评》为你而备,租房无忧!再也不用担心被欺骗,想要知道给你介绍房子的人好不好,《租房点评》告诉你!"
通过writeToFile方法,将一些对象写入到文件中
do { try info.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding) } catch let error as NSError { print(error)//如果创建失败,error 会返回错误信息 }
//保存图片 let image = UIImage(named: "SwiftClassWeiXin@3x.png") let data:NSData = UIImageJPEGRepresentation(image!, 1.0)! let data1:NSData = UIImagePNGRepresentation(image!)! data.writeToFile(myDirectory1 + "/SwiftClassIcon.jpg", atomically: true) data1.writeToFile(myDirectory1 + "/SwiftClassIcon.png", atomically: true) //保存NSArray let array = NSArray(objects: "111","222","333") array.writeToFile(myDirectory4 + "/array.plist", atomically: true) //保存NSDic let dictionary = NSDictionary(objects: ["1111","22222","33333"], forKeys: ["1","2","3"]) dictionary.writeToFile(myDirectory4 + "/dictionary.plist", atomically: true)
//判断目录或文件是否存在 let exist = fileManager.fileExistsAtPath(filePath) print(exist) //移动 let filePath2 = myDirectory4 + "/appInfo.txt" do { try fileManager.moveItemAtPath(filePath, toPath: filePath2) } catch let error as NSError { print(error)//如果创建失败,error 会返回错误信息 } //重命名 //通过移动该文件对文件重命名 let filePath3 = myDirectory4 + "/appInfo2.txt" do { try fileManager.moveItemAtPath(filePath2, toPath: filePath3) } catch let error as NSError { print(error)//如果创建失败,error 会返回错误信息 } //拷贝 let filePath4 = myDirectory4 + "/appInfoCopy.txt" do { try fileManager.copyItemAtPath(filePath3, toPath: filePath4) } catch let error as NSError { print(error)//如果创建失败,error 会返回错误信息 }
//获取目录列里所有文件名 //先拷贝一些文件到myDirectory4目录下 let filePath00 = myDirectory4 + "/appInfoCopy00.txt" let filePath11 = myDirectory4 + "/appInfoCopy11.txt" let filePath22 = myDirectory4 + "/appInfoCopy22.txt" do { try fileManager.copyItemAtPath(filePath3, toPath: filePath00) try fileManager.copyItemAtPath(filePath3, toPath: filePath11) try fileManager.copyItemAtPath(filePath3, toPath: filePath22) } catch let error as NSError { print(error)//如果创建失败,error 会返回错误信息 }
//获取所有文件 let fileArray = fileManager.subpathsAtPath(myDirectory4) print(fileArray) // Optional([appInfo.txt, appInfo2.txt, appInfoCopy.txt, appInfoCopy00.txt, appInfoCopy11.txt, appInfoCopy22.txt]) //iPhone中获取文件各项属性方法 //获取文件属性 do { var fileAttributes : [NSObject:AnyObject]? = try NSFileManager.defaultManager().attributesOfItemAtPath(filePath22) //获取文件的创建日期 let modificationDate:AnyObject? = fileAttributes![NSFileModificationDate] print(modificationDate) //获取文件的字节大小 let fileSize:AnyObject? = fileAttributes![NSFileSize] print(fileSize) } catch let error as NSError { print(error)//如果创建失败,error 会返回错误信息 }
//删除文件 do { try fileManager.removeItemAtPath(filePath4) } catch let error as NSError { print(error)//如果创建失败,error 会返回错误信息 } //删除目录下所有文件 //方法1: 获取所有文件,然后遍历删除 let fileArray2 : [AnyObject]? = fileManager.subpathsAtPath(myDirectory4) for fn in fileArray2! { do { try fileManager.removeItemAtPath(myDirectory4 + "/\(fn)") } catch let error as NSError { print(error)//如果创建失败,error 会返回错误信息 } } //方法2:删除目录后重新创建该目录 do { try fileManager.removeItemAtPath(myDirectory4) try fileManager.createDirectoryAtPath(myDirectory4, withIntermediateDirectories: true, attributes: nil) } catch let error as NSError { print(error)//如果创建失败,error 会返回错误信息 } }