1

I was trying to make a module using Swift that can add a class to the database(ClassA.plist). The code is like this:

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()
    }
}

And my storyboard is like this:

Storyboard Save Button

However, as I write something in the textfield and click Save, nothing changed in my database. No waring, error or logs is shown.Does anyone know how to solve this problem?

David
  • 339
  • 1
  • 3
  • 10

2 Answers2

1

You can't write to a file in the app bundle. The app bundle is read-only. You will need to copy your file to one of your sandbox directories like the documents directory before you will be able to change it.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
0

As many have pointed out, the app's bundle is read-only. What you can do is copy the file if you really want to use it and put it in the documentDirectory where you can read and write to it.

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)
Christian Abella
  • 5,747
  • 2
  • 30
  • 42