arrays - NSUserDefaults 在 tableview 中作为数组保存和读取

标签 arrays swift tableview nsuserdefaults

好的,所以我让用户在文本字段中输入名称,然后按钮将名称传递到另一个 View 中的 TableView , TableView 列出名称,但是当添加新名称时,它会覆盖以前的名称,而不是列出所有名称添加到 TableView 的名称。这是我的代码:

View Controller 1:

     @IBAction func addPlant(sender: AnyObject) {



        let array = self.title
        NSUserDefaults.standardUserDefaults().setObject(array, forKey: "userName")
        NSUserDefaults.standardUserDefaults().synchronize()
}

View Controller 2:

    @IBOutlet weak var tableView: UITableView!

var userDefaults = NSUserDefaults.standardUserDefaults()

var ourText = String()

var textArray:[String] = [String]()

override func viewDidLoad() {
    super.viewDidLoad()


    //self.tableview.delegate = self
    self.tableView.dataSource = self

    ourText = userDefaults.stringForKey("userName")!
    textArray.append(ourText)



}

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

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

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) 
    cell.textLabel?.text = textArray[indexPath.row]

    return cell
}

最佳答案

你可以使用

 textArray = NSUserDefaults.standardUserDefaults().arrayForKey("userName") 

或者

 textArray = NSUserDefaults.standardUserDefaults().objectForKey("userName")

关于arrays - NSUserDefaults 在 tableview 中作为数组保存和读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35873431/

相关文章:

c++ - 将 C++ 中的动态分配数组的大小调整为较小的大小

objective-c - 使用 Storyboard在 Xcode 6 os x 应用程序中更改不同的 View

ios - 在 Xcode 9.2 中检索 Firebase 数据库引用时出错

JavaFX:从 tableview 中删除空行

ios - "Type' 程序 ' does not conform to protocol ' 任何对象 '"

javascript - JSON数组删除语音标记?

javascript - 根据部分重复项连接行

ios - 阻止在 TableView 的特定单元格中重新排序

c - 数组的最大索引及其在平台上的长度

ios - 在 tableView 中加载 .gif