ios - Swift 2.2 - NSUserDefaults 不工作并添加到列表 iOS

标签 ios swift nsuserdefaults

当我使用 NSUserDefaults 时,它无法正常工作并重新加载 tableView 上的数据。我有一个添加项目的页面,但它显示添加的项目,当我再次打开它时,它没有保存。这是我的完整代码。

import UIKit

var noteTitles = [String]()
var text = [String]()

class TableViewController: UITableViewController {

  override func viewDidAppear(animated: Bool) {
    tableView.reloadData()
  }

  override func viewDidLoad() {
    super.viewDidLoad()

    if NSUserDefaults.standardUserDefaults().objectForKey("note") != nil {

      noteTitles = NSUserDefaults.standardUserDefaults().objectForKey("note") as! [String]

    }

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem()
  }

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

  // MARK: - Table view data source

  override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
  }

  override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return noteTitles.count
  }


  override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell

    cell.textLabel?.text = noteTitles[indexPath.row]

    // Configure the cell...

    return cell
  }

我不知道出了什么问题,Xcode 也没有显示任何错误或警告。我做错了什么,我该如何解决?

最佳答案

我不知道你在哪里保存了你的值。

必须先保存,然后调用synchronize方法才能保存值。

NSUserDefaults.standUserDefaults().setObject(noteTitles, forKey: "note")
NSUserDefaults.standardUserDefaults().synchronize()

关于ios - Swift 2.2 - NSUserDefaults 不工作并添加到列表 iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38318524/

相关文章:

ios - 将字符串保存到 NSUserDefaults?

ios - 仅使用生产证书时无法注册推送通知

ios - 在 Xcode 7.2 中添加 Font Awesome 时出现问题

iphone - 如何将选择器 View 的标题获取到文本字段

ios - 将可选的@objc 枚举类型传递给@objc 协议(protocol)

ios - 设置 UIProgressView 进度时不需要的高度约束动画

ios - 在 iOS 中使用 Swift 语言将下载的文件解压缩到同一文件夹中

iphone - NSUserDefaults 中的 NSDate 问题

ios - NSUserDefault 无法检索 double 值

iOS TESSERACT : Disable Dictionary