2016-04-01 8 views
1

私はplistファイルを持っています。各テキストフィールドやスイッチを書き終えると、値が正しく保存され、テーブルが正しく更新され、情報が正しく反映されます。しかし、私は、画面とリターンを変更すると、私のplistファイルが空で、私はいくつかのオプションをチェックしてください。plistファイルを書くswift

... 

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

私のチュートリアル(http://rebeloper.com/read-write-plist-file-swift/)がSwift 3.1にアップデートされました。それを見てみましょう。 – Rebeloper

答えて

2

いくつか:

まず、最初のコードブロックは機能しません。アプリバンドルは読み取り専用です。バンドルにファイルを書き込もうとすると、常に失敗します。

次に、プロパティリストには非常に小さなオブジェクトのセットしか含めることができません。これらのオブジェクトはすべてNSObjectsでなければなりません。詳細については、Xcodeの「プロパティリストオブジェクト」で検索してください。

あなたが呼び出す関数writeToFile(辞書または配列?)は、Boolを返します。結果が失敗していないかどうかを確認してください。

1

これは私の方法です。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 
    } 
} 
0

アップデートスウィフト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.") 
} 

Read and write plist file switf

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 

} 
すでに前に行われていない場合 のplistは自動的にドキュメントディレクトリにコピーされます

}

関連する問題