数据存储--writeToFile--Swift

var array: NSArray!

var dic :NSDictionary!

var nameStr: NSString!


//writeToFile:使数据持久化的一种操作方式

/*

存数据

1.找文件路径

2.使用writeToFile:把数据写入本地

读数据

1.找文件路径

2.使用数据形式所对应的对象来接收数据

*/


/*                ******* 1.创建数组  *******            */

array = ["持","久","化"]

//2.找到沙盒里Document文件夹的路径

let documentPathArray = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)

//找Document文件夹的路径的元素

let documentPath = documentPathArray[0]

//找路径

let plistFilePath = documentPath.appending("/数据.plist")

print(plistFilePath)

// 4.存数据

/*

(1)part1写入的文件路径

(2)part2如果写yes 系统会自动创建临时路径去保存完成后  把数据移动到最终路径,防止文件写入错误问题

(3)no直接写入最终路径

*/

let isSuccess = array.write(toFile: plistFilePath, atomically: true)

isSuccess ? print("写入成功") :print("写入失败")

//5.读取数据

let array1 = NSArray(contentsOfFile: plistFilePath)

print(array1?.count)

print(array1)


/*                ******* 2.写入字典  *******            */

//1.创建字典

dic = ["1":"游戏","2":"德玛"]

//2.找到沙盒里Document文件夹的路径(返回的是数组)

var documentsPathADic = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)

//找Document文件夹的路径的元素(返回的是字符串)

let documentsPathDic = documentsPathADic[0]

//找路径(返回的是字符串)

let plistDocumentsPathDic = documentsPathDic.appending("字典.plist")

//3.写入

let isDicIsSuccess = dic.write(toFile: plistDocumentsPathDic, atomically: true)

isDicIsSuccess ? print("字典写入成功") : print("字典写入失败")

//4.读出字典

let dic1 = NSDictionary(contentsOfFile: plistDocumentsPathDic)

for string in (dic1?.allValues)! {

print(string)

}


/*                ******* 3.写入字符串  *******            */

nameStr = "鱼香肉丝"

//1.封装文件路径调用

let nameFilePath = self.filePath(filename: nameStr)

/*

(1)encoding  编码格式      NSUTF8StringEncoding  比较常用 万国编码

(2)error :写入错误  一般写nil

(3)NSError *error;

*/

//2.写入字符串

try! nameStr.write(toFile: nameFilePath as String, atomically: true, encoding:String.Encoding.utf8.rawValue)

//isStrSuccess ? print("写入成功") : print("写入失败")

//3.读出字符串

let nameStr1 = try! String(contentsOfFile: nameFilePath, encoding: String.Encoding.utf8)

print("My ZiFuChuan is \(nameStr1)")


/*              ******* 4.存NSData 二进制数据 *******          */

//创建字符串

let dataStr = "老干妈"

//字符串转换成二进制数据

let data = dataStr.data(using: String.Encoding.utf8) as! NSData

//封装文件路径

let dataFilePath = self.filePath(filename: "美味可口")

//写入data

let isDataSuccess =  data.write(toFile: dataFilePath, atomically: true)

isDataSuccess ? print("二进制写入成功") : print("二进制写入失败")

//读出data

let readData = NSData.init(contentsOfFile: dataFilePath)

let strData = NSString.init(data: readData as! Data, encoding: String.Encoding.utf8.rawValue)

print("My data is \(strData)")

}

func filePath(filename:NSString) ->String {

let documentsPathArray = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)

let documentsPath = documentsPathArray[0]

let  plistPath = documentsPath.appending(filename as String)

return plistPath

}

你可能感兴趣的:(数据存储--writeToFile--Swift)