数据存储NSData

一、 字符串存储

let str = "Hello, World!"

//第一个参数是转化成编码的格式,第二个参数是在编码过程中是否允许删减或替换

let utf8Str = str.data(using: String.Encoding.utf8, allowLossyConversion: true)

二、初始化方法

1 、let withd = NSData(data:utf8Str!)


2、let url = NSURL(string:"https:baidu.com")
      let withURL = NSData.init(contentsOf: url as! URL)
      print(withURL!)

3、let file = Bundle.main.path(forResource: "text", ofType: "plist")
      let withPath = NSData.init(contentsOfFile: file!)

三、访问数据

 1、let utf8Str = str.data(using: String.Encoding.utf8, allowLossyConversion: true)

       let des = utf8Str?.description

 2、详细信息

   let utf8Str: NSData! = str.data(using: String.Encoding.utf8, allowLossyConversion: true) as NSData!
   var bytes = utf8Str.bytes
   var string = NSString.init(bytes: bytes, length: utf8Str.length, encoding: String.Encoding.utf8.rawValue)
   print(string!)

四、字节数据存储

   let strPath = "所要存储的信息"
   let utf8data:NSData! = strPath.data(using: String.Encoding.utf8, allowLossyConversion: true) as NSData!
   var pathArray = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)

   let defaultPath = pathArray[0]
   let  textpath = defaultPath + "/text.txt"
   print(textpath)
   let  result = utf8data.write(toFile: strPath, atomically: true)

   //数据的读取

let datas = NSData.init(contentsOfFile: textpath)
let utf8Str = NSString.init(data: datas as! Data, encoding: String.Encoding.utf8.rawValue)
print(utf8Str!)

   /**********************/ 访问路径方法

   let path = Bundle.main.path(forResource: "text", ofType: "txt")

   /************/

阅读更多
文章标签: ios swift 数据存储
个人分类: swift
上一篇字符串
下一篇UILabel
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭