我有一个plist文件,这个文件用设置填充表单;当我写完每个文本字段或切换时,值正确保存,正确刷新我的表格,我的信息正确。但是当我更改屏幕并返回时,我的plist文件为空,我检查了几个选项:
...
let path = NSBundle.mainBundle().pathForResource("perfilBitrubian", ofType: "plist")
descripcionCelda.writeToFile(path!, atomically: false)
或
...
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let documentsDirectory = paths.objectAtIndex(0) as! NSString
let path = documentsDirectory.stringByAppendingPathComponent("perfilBitrubian.plist")
descripcionCelda.writeToFile(path!, atomically: false)
我的列表有隐藏的选项;当我隐藏并显示我的表正确刷新数据,但如果我改变过程并返回表单;我的plist文件没有信息。
我看到这个例子,我不知道该怎么做。
http://rebeloper.com/read-write-plist-file-swift/
和此:
http://www.appcoda.com/expandable-table-view/
谢谢!
答案 0 :(得分:2)
有几件事:
首先,您的第一个代码块将无效。应用包是只读的。尝试将文件写入捆绑包将始终失败。
接下来,属性列表只能包含一小组对象,所有对象都必须是NSObjects。在Xcode中搜索“属性列表对象”以获取更多信息。
您正在调用的函数writeToFile
(在字典或数组上?)返回Bool。检查结果,看它是否失败。
答案 1 :(得分:1)
这些是我的方法,你必须传递plist名称(没有扩展名),写入也传递密钥和字典或数组。 如果之前尚未完成,则plist会自动复制到文档目录:
public static func plistRead(plistName: String) -> [String: AnyObject]? {
let path = documentsPath().stringByAppendingPathComponent(plistName + ".plist")
let fileManager = NSFileManager.defaultManager()
if !(fileManager.fileExistsAtPath(path)) {
if let bundlePath = NSBundle.mainBundle().pathForResource(plistName, ofType: "plist") {
do {
try fileManager.copyItemAtPath(bundlePath, toPath: path)
} catch let error as NSError {
print("Can't move plist from bundle to documents directory: " + error.localizedDescription)
}
} else {
print("No plist found!")
}
}
return NSDictionary(contentsOfFile: path) as? [String: AnyObject]
}
public static func plistWrite(plistName: String, key: String, data: AnyObject?) -> Bool {
let path = documentsPath().stringByAppendingPathComponent(plistName + ".plist")
let fileManager = NSFileManager.defaultManager()
if !(fileManager.fileExistsAtPath(path)) {
if let bundlePath = NSBundle.mainBundle().pathForResource(plistName, ofType: "plist") {
do {
try fileManager.copyItemAtPath(bundlePath, toPath: path)
} catch let error as NSError {
print("Can't move plist from bundle to documents directory: " + error.localizedDescription)
return false
}
} else {
print("No plist found!")
return false
}
}
if let savedStock = NSMutableDictionary(contentsOfFile: path) {
if let data = data { savedStock.setObject(data, forKey: key) }
else { savedStock.removeObjectForKey(key) }
if savedStock.writeToFile(path, atomically: true) { return true }
else {
print("Can't save file at path: \(path)")
return false
}
}
else {
print("Can't create dictionary!")
return false
}
}
答案 2 :(得分:0)
更新swift 3
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
let documentDirectory = paths[0] as! String
let path = documentDirectory.appending("myData.plist")
let fileManager = FileManager.default
if(!fileManager.fileExists(atPath: path)){
if let bundlePath = Bundle.main.path(forResource: "myData", ofType: "plist"){
let result = NSMutableDictionary(contentsOfFile: bundlePath)
print("Bundle file myData.plist is -> \(result?.description)")
do{
try fileManager.copyItem(atPath: bundlePath, toPath: path)
}catch{
print("copy failure.")
}
}else{
print("file myData.plist not found.")
}
}else{
print("file myData.plist already exits at path.")
}
let resultDictionary = NSMutableDictionary(contentsOfFile: path)
print("load myData.plist is ->\(resultDictionary?.description)")
let myDict = NSDictionary(contentsOfFile: path)
if let dict = myDict{
myItemValue = dict.object(forKey: myItemKey) as! String?
txtValue.text = myItemValue
}else{
print("load failure.")
}
答案 3 :(得分:0)
类MainTableViewController:UITableViewController {
//MARK:- Properties
//reading data
var tableData = [String]()
//writing data
var dicData: NSMutableDictionary = ["name" : "data"]
//MARK:- View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
/* converting path to document directory since plist in bundle can't be modified */
let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
let path : NSString = documentsDirectory.appendingPathComponent("TableDataPropertyList.plist") as NSString
/* getting the path and paste the path in finder to see the plist in document directory */
print(" \(path) ")
dicData.write(toFile: path as String, atomically: false)
//path of plist in bundle to read
let mainPath = Bundle.main.path(forResource: "TableDataPropertyList", ofType: "plist")
let dict = NSDictionary(contentsOfFile: (mainPath)! as String)
tableData = dict!.object(forKey: "AppleDevice") as! [String]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellIdentifier", for: indexPath as IndexPath)
cell.textLabel!.text = tableData[indexPath.row]
return cell
}
}