//关于目录的获取 //获取沙盒目录(算是跟目录吧) NSHomeDirectory() //获取document目录(常用) let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first //或者 FileManager().urls(for: .documentDirectory, in: .userDomainMask).first! //获取library目录 var libraryPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true) //获取caches(缓存目录)目录 var cachesPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true) //获取temp目录 var tempPath = NSTemporaryDirectory() //关于fileManager对象的常用操作 //创建文件管理员(相当于我们hibernate的sessionFactory) let fileManager = FileManager.default //判读文件或目录是否存在 let result = fileManager.fileExists(atPath: path) //新增目录 try! fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil) //删除目录或文件 try! fileManager.removeItem(atPath: path) //创建文件 fileManager.createFile(atPath: path, contents: nil, attributes: nil) //关于userDefault的常用操作 //获取userDefault的实例 let userDefaults = UserDefaults.standard //往实例里对数据 userDefaults.set(Date(), forKey: refreshKey) //数据从实例里取出来并强制回原来类型 let date = userDefaults.object(forKey: refreshKey) as? Date //关于创建plist的数组或字典的写入和读取操作 // 构建路径 let namesPath = "\(documentsPath)/names.plist" // 名字的数组 let names: NSArray = ["aaa", "bbb", "ccc", "maizixueyuan"] names.write(toFile: namesPath, atomically: true) // 读取数据,输出结果 let entries = NSArray(contentsOfFile: namesPath)! print(entries) //------------------------------ // 构建路径 let studentsPath = "\(documentsPath)/students.plist" // 学生的字典 let students: NSDictionary = ["sno": "1101", "name": "maizixueyuan", "score": 100] students.write(toFile: studentsPath, atomically: true) // 读取数据,输出结果 let data = NSDictionary(contentsOfFile: studentsPath)!
时间: 2024-10-08 17:21:43