如何将字符串I附加到字符串数组中,然后使用Swift 2将其永久存储到内存中?

时间:2016-02-19 20:40:03

标签: ios iphone swift2 xcode7

我一直在尝试创建一个具有预先存在的字符串数组的简单应用程序,当在UIAlertController内部时,您可以通过文本框向列表中添加更多项目。我已经在整个地方尝试过NSUserDefault声明,但这些对象都没有存储到内存中。这是我的ViewController类:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet weak var tableView: UITableView!

var names = ["Stow the TV antenna", "Stow the awning", "Retract stabilizer jacks", "Store wood blocks", "Plug in trailer lights", "Hookup the breakaway chains", "Make sure the trailer lights work", "Drain waste tanks and store hose", "Unplug sources of electrical power", "Stow chairs, dog rope, etc.", "Douse the campfire completely", "Stow the TV", "Ensure the fridge is closed and stable", "Switch fridge to gas", "Close all compartments", "Pick up everything", "Close the vents and windows", "Turn off the water pump"]


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return names.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomCell

    cell.name.text = names[indexPath.row]

    return cell
}

@IBAction func pressAdd(sender: AnyObject) {
    // Display the warning
    displayAddItem("Add Tasks", message: "Add more tasks to the list")
}

@IBAction func pressShare(sender: AnyObject) {
    // Check to see if table is empty
    if (names.isEmpty) {
        displayAlert("Warning", message: "Your list has no tasks!")
    }

        // If there are contents
    else {
        displayShareSheet("Share your list")
    }
}

func displayAlert(title: String, message: String) {
    let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
    alertController.addAction(UIAlertAction(title: "OK", style:
        .Default, handler: nil))
    presentViewController(alertController, animated: true, completion: {})
    return
}

func displayShareSheet(shareContent:String) {
    let activityViewController = UIActivityViewController(activityItems: [shareContent as NSString], applicationActivities: nil)
    presentViewController(activityViewController, animated: true, completion: {})
}

func displayAddItem(title: String, message: String) {
    var inputTextField: UITextField?

    let addItemController = UIAlertController(title: title, message: message, preferredStyle: .Alert)

    addItemController.addTextFieldWithConfigurationHandler { (textField : UITextField!) -> Void in
        textField.placeholder = "Add a task"
        inputTextField = textField

    }

    let saveAction = UIAlertAction(title: "Add", style: UIAlertActionStyle.Default, handler: {
        alert -> Void in
        if (inputTextField!.text != "") {

            if let itemText = inputTextField {
                let stringToAdd = itemText.text
                self.names.append(stringToAdd!)
                NSUserDefaults.standardUserDefaults().setObject(self.names, forKey: "arr")
                self.tableView.reloadData()
            }
        }

    })

    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)


    addItemController.addAction(saveAction)
    addItemController.addAction(cancelAction)

    self.presentViewController(addItemController, animated: true, completion: nil)

}

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == UITableViewCellEditingStyle.Delete {
        names.removeAtIndex(indexPath.row)
        NSUserDefaults.standardUserDefaults().setObject(names, forKey: "arr")
        tableView.reloadData()
    }
}

使用我所拥有的,如何使用我的saveAction从textField写入String以附加到我的“names”数组并将其永久存储在内存中?谢谢!

2 个答案:

答案 0 :(得分:1)

在我看来,您没有从NSUserDefaults中检索信息。为此,您需要致电:

NSUserDefaults.standardUserDefaults().arrayForKey("arr")

话虽如此,NSUserDefaults旨在成为保存用户首选项而不是保留业务对象的地方。

如果要进行扩展,我建议您查看其他替代方法,以保留Core DataRealm等数据。

答案 1 :(得分:-1)

要在iOS设备上存储数据,您必须使用CoreData或替代,您必须使用.csv数据解决此问题。 CoreData是由Apple开发的用于iOS应用程序的数据库,用于永久存储数据,而.csv数据不是"罚款"解决方案,但比CoreData简单得多。所以你必须选择其中一个解决方案听起来更好;)我确定你在YouTube或谷歌上找到了很多关于这个主题的教程。希望我能帮助这些信息好运! ;)