2016-12-05 33 views
1

我想使用Swift創建一個模塊,可以將一個類添加到數據庫(ClassA.plist)。該代碼是這樣的:爲什麼我的數據沒有寫入plist文件?

class AddClass:UITableViewController { 
@IBOutlet weak var txtClassName: UITextField! 


@IBAction func Save(_ sender: Any) { 
    let plistPath = Bundle.main.path(forResource: "ClassA", ofType:"plist") 
    let array = NSMutableArray(contentsOfFile: plistPath!) 
    let AddData = NSDictionary(object: txtClassName.text!, forKey: "name" as NSCopying) 

    array?.add(AddData) 

    array?.write(toFile: plistPath!, atomically: false) 
    DispatchQueue.main.async { 
     super.tableView.reloadData() 
    } 
} 

我的故事板是這樣的:

Storyboard Save Button

然而,正如我寫在文本框的東西,然後點擊保存,沒有在我的數據庫中更改。沒有waring,錯誤或日誌顯示。有誰知道如何解決這個問題?

+0

,您是否試圖dictionery代替陣列 –

+0

使用,如果它使這個答案sense.http://stackoverflow.com/questions/6697247/how-to-create-plist-files-programmatically-in-iphone –

+0

正如其他許多帖子所寫,應用程序的包是隻讀的。 – rmaddy

回答

0

你不能寫在應用程序包中的文件。應用程序包是隻讀的。您需要將文件複製到您的沙箱目錄之一(如文檔目錄),然後才能對其進行更改。

+0

有很多重複項可以關閉,但我在Swift中找不到任何重複項。 – rmaddy

+0

而現在得益於基督教,這個線程可以是斯威夫特回答這個長期存在的問題... –

+0

其實,我終於找到了一個 - 這是你的答案。 – rmaddy

0

正如許多人所指出的那樣,應用程序的包是隻讀的。你可以做的是複製文件,如果你真的想使用它,並把它放在documentDirectory中,你可以讀寫它。

let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String 
let plistPath = paths.appending("/data.plist") 
let fileManager = FileManager.default 

if !fileManager.fileExists(atPath: plistPath) 
{ 
    // Default plist name is Info. Just using ClassA 
    let bundle = Bundle.main.path(forResource: "ClassA", ofType: "plist") 
    try! fileManager.copyItem(atPath: bundle!, toPath: plistPath) 
} 


let data = NSMutableDictionary(contentsOfFile: plistPath) 

data?.setObject("Hello World", forKey: "name" as NSCopying) 
data?.write(toFile: plistPath, atomically: true) 

print(data) 
相關問題