美文网首页Swift点点滴滴
Swift之数据管理(一)

Swift之数据管理(一)

作者: 就怕是个demo | 来源:发表于2015-12-23 15:30 被阅读137次

1、获取文件路径

//1. Home目录, 即沙盒目录
var path = NSHomeDirectory()
print("Home path: \(path)")
    
//2. Documents目录 .UserDomainMask -->搜索范围限制在该应用程序的沙盒内 true -->是否显示完整路径  first -->结果为数组,这里取第一个内容
path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
print("Documents: \(path)")
    
//3. Library目录
path = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true).first!
print("Library: \(path)")
    
//4. Caches目录
path = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first!
print("Caches: \(path)")
    
//5. tmp目录
path = NSTemporaryDirectory()
print("Tmp: \(path)")
  1. 目录文件管理
//检测目录是否存在
path = "\(path)/Data"
let fileManager = NSFileManager.defaultManager()
let result = fileManager.fileExistsAtPath(path)
print(result)

//创建目录
//withIntermediateDirectories 如果新文件夹路径有多级则设为true
let fileManager = NSFileManager.defaultManager()
do {
    try fileManager.createDirectoryAtPath(path, withIntermediateDirectories: false, attributes: nil)
} catch {
    print("create directory failed")
}

//删除目录
let fileManager = NSFileManager.defaultManager()
do {
    try fileManager.removeItemAtPath(path)
} catch {
    print("delete directory failed")
}

//创建文件
fileManager.createFileAtPath(path, contents: nil, attributes: nil)
  1. 用户首选项(与Android的shared preferences类似)
//获取对象实例
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject("CrazyMse", forKey: "NAME")
userDefaults.setObject("Joker", forKey: "NAME1")
userDefaults.synchronize() //同步数据到本地

//获取本地内容
let name = userDefaults.objectForKey("NAME")
let name1 = userDefaults.objectForKey("NAME1")
print("\(name!)------\(name1!)")
  1. 属性列表
lazy var documentsPath: String = {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    return paths.first!
}()

//数组操作
//构造路径
let namesPaths = "\(documentsPath)/names.plist"
print(namesPaths)
//名字的数组 注意:最好用NSArray,否则会出问题
let names: NSArray = ["aaa", "bbb", "ccc", "CrazyMouse"]
names.writeToFile(namesPaths, atomically: true)//atomically 为true时,写入临时文件,待写完后无错误,才写入到文件中
//读取数据
let entries = NSArray(contentsOfFile: namesPaths)
print(entries!)
    
//字典操作
//构造路径
let studentsPath = "\(documentsPath)/students.plist"
//学生字典 注意:最好用NSDictionary,否则会出问题
let students: NSDictionary = ["sno": "1101", "name": "CrazyMouse", "score": 100]
students.writeToFile(studentsPath, atomically: true)
//读取数据
let data = NSDictionary(contentsOfFile: studentsPath)
print(data!.objectForKey("name")!)

相关文章

网友评论

    本文标题:Swift之数据管理(一)

    本文链接:https://www.haomeiwen.com/subject/fvkvhttx.html