ios中数据持久化存储方式一般有5种:NSUserDefault、对象归档(NSKeyedArchiver)、文件操作、数据库存储(SQLite3)、CoreData。
1、NSUserDefault用于保存程序相关的偏好设置和配置数据等,以便下次启动程序后能恢复上次的设置。
NSUserDefault和对象归档
//通过单利来创建一个NSUserDefaults对象,全局变量NSUserDefault,可在整个项目传递变量
let userDefault:NSUserDefaults = NSUserDefaults.standardUserDefaults() //通过init方法创建
let userDefault1:NSUserDefaults = NSUserDefaults(suiteName: "SwiftClass")!
print(userDefault1.dictionaryRepresentation()) //获取userDefault单利下所有的值
print(userDefault.dictionaryRepresentation()) //判断NSUserDefaults的“appMessage”key 在dictionaryRepresentation中是否存在,如果不存在就设置“appMessage”值为This is app message。
if(userDefault.objectForKey("message") == nil){
userDefault.setObject("This_is_my_default_message", forKey: "message")
} //如果想单独看某个key的设置,例如:
let dic = userDefault.dictionaryRepresentation()
let object_one:AnyObject? = (dic as NSDictionary).objectForKey("AppleKeyboards")
// //或者
// var object_one:AnyObject? = dic["AppleKeyboards"] if let oValue: AnyObject! = object_one {
print(oValue)
} //Int类型
//设置
userDefault.setInteger(, forKey: "Int")
//读取
let intValue = userDefault.integerForKey("Int")
print(intValue) //Float类型
//设置
userDefault.setFloat(3.2, forKey: "Float")
//读取
let floatValue = userDefault.floatForKey("Float")
print(floatValue) //Double类
//设置
userDefault.setDouble(5.6890, forKey: "Double")
//读取
let doubleValue = userDefault.doubleForKey("Double")
print(doubleValue) //Bool类型
//设置
userDefault.setBool(true, forKey: "Bool")
//读取
let boolValue = userDefault.boolForKey("Bool")
print(boolValue) //NSURL类型
//设置
userDefault.setURL(NSURL(string: "http://www.iphonetrain.com")!, forKey: "NSURL")
//读取
let urlValue = userDefault.URLForKey("NSURL")
print(urlValue)
//保存NSDate数据
//将对象转换成NSData流
let imageData:NSData = NSKeyedArchiver.archivedDataWithRootObject(UIImage(named: "SwiftClassWeiXin.png")!) //存储NSData对象
userDefault.setObject(imageData, forKey: "imageData") //读取数据
//获取NSData
let objData:AnyObject? = userDefault.objectForKey("imageData") //还原对象-初始一个UIImage对象
let myImage:AnyObject? = NSKeyedUnarchiver.unarchiveObjectWithData(objData as! NSData) print(myImage)
//自定义的类实现存取需要通过NSData做载体 //创建AppsModel的实例
let model = AppsModel(imageName: "appIcon2.png", app_Name: "租房点评", app_Description: "租房被骗?现在开始,你来改变这一切!《租房点评》为你而备,租房无忧!") //实例对象转换成NSData
let modelData:NSData = NSKeyedArchiver.archivedDataWithRootObject(model) //存储NSData对象
userDefault.setObject(modelData, forKey: "myAppModel")
//保存NSString,
userDefault.setValue("1_NSString", forKey: "NSString")
userDefault.setObject("1_NSString1", forKey: "NSString1") //保存NSNumber,
let number:NSNumber = NSNumber(int: )
userDefault.setValue(number, forKey: "number")
userDefault.setObject(number, forKey: "number1") //保存NSArray
let array1:NSArray = NSArray(array:["",""])
userDefault.setValue(array1, forKey: "array")
userDefault.setObject(array1, forKey: "array1") //保存NSDictionary
let dictionary:NSDictionary = NSDictionary(dictionary: ["":""])
userDefault.setValue(dictionary, forKey: "dictionary")
userDefault.setObject(dictionary, forKey: "dictionary1")
var value:AnyObject? = userDefault.valueForKey("dictionary")
print(value) value = userDefault.objectForKey("dictionary1")
print(value) //-------- 删除所有的值
let ar:NSDictionary = userDefault.dictionaryRepresentation() for key in ar.allKeys { userDefault.removeObjectForKey(key as! String) userDefault.synchronize()//内存中数据同步更新数据库
}
2、文件操作
应用开发中所有的非代码文件都存储在沙盒中。
//1、获取程序的Home目录
let homeDirectory = NSHomeDirectory()
print(homeDirectory) //2、获取Documents目录
let documentPaths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) let documentPath = documentPaths[]
print(documentPath) //或通过home目录自己追加文件夹
let documentPath2 = homeDirectory + "/Documents"
print(documentPath2) //3、获取Library目录
let libraryPaths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let libraryPath = libraryPaths[]
print(libraryPath) //或通过home目录自己追加文件夹
let libraryPath2 = homeDirectory + "/Library"
print(libraryPath2) //4、获取Cache目录
let cachesPaths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let cachesPath = cachesPaths[]
print(cachesPath) //或通过home目录自己追加文件夹
let cachesPath2 = homeDirectory + "/Library/Caches"
print(cachesPath2) //5、获取Tmp目录
let tmpDir = NSTemporaryDirectory()
print(tmpDir) //或通过home目录自己追加文件夹
let tmpDir2 = homeDirectory + "/tmp"
print(tmpDir2)
对文件操作需要先创建一个文件管理器
// 创建文件管理器
let fileManager :NSFileManager = NSFileManager.defaultManager()
//创建目录
//定义几个自己的目录
let myDirectory1:String = NSHomeDirectory() + "/Documents/myFolder/Images"
let myDirectory2:String = NSHomeDirectory() + "/Documents/myFolder/Films"
let myDirectory3:String = NSHomeDirectory() + "/Documents/myFolder/Musics"
let myDirectory4:String = NSHomeDirectory() + "/Documents/myFolder/Files" //创建目录
//withIntermediateDirectories 设置成true,代表中间所有的路径目录如果不存在,都会创建
//如果设置成false,因为myFolder目录不存在,所以无法创建1234目录 //创建myDirectory1目录
do
{
try fileManager.createDirectoryAtPath(myDirectory1, withIntermediateDirectories: true, attributes: nil)
}
catch let error as NSError {
print(error)//如果创建失败,error 会返回错误信息
} //创建myDirectory2目录
do
{
try fileManager.createDirectoryAtPath(myDirectory2, withIntermediateDirectories: true, attributes: nil)
}
catch let error as NSError {
print(error)//如果创建失败,error 会返回错误信息
} //创建myDirectory3目录
do
{
try fileManager.createDirectoryAtPath(myDirectory3, withIntermediateDirectories: true, attributes: nil)
}
catch let error as NSError {
print(error)//如果创建失败,error 会返回错误信息
} //创建myDirectory4目录
do
{
try fileManager.createDirectoryAtPath(myDirectory4, withIntermediateDirectories: true, attributes: nil)
}
catch let error as NSError {
print(error)//如果创建失败,error 会返回错误信息
}
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: "","","")
array.writeToFile(myDirectory4 + "/array.plist", atomically: true) //保存NSDic
let dictionary = NSDictionary(objects: ["","",""], forKeys: ["","",""])
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 会返回错误信息
}
}