关于NSUserDefaults选中行值重存及数组UITableView展示的技术咨询
Hey there! Let's walk through each of your needs with clear, actionable code and explanations:
1. Update NSUserDefaults Value Based on Selected TableView Row
When the user selects a row in your second ViewController's UITableView, you'll need to fetch the selected entry, update its value, save the modified array back to NSUserDefaults, and refresh the table to show changes. Here's how to do it:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // Grab the selected user entry from the array var selectedUser = userInfo[indexPath.row] // Update the target key-value pair (replace with your actual update logic) selectedUser["city"] = "Updated City Name" // Replace the old entry with the updated one in the array userInfo[indexPath.row] = selectedUser // Save the modified array back to NSUserDefaults UserDefaults.standard.set(userInfo, forKey: "userInfo") // Refresh the specific row to reflect changes tableView.reloadRows(at: [indexPath], with: .fade) }
2. Fix the Array Saving Logic in First ViewController
Your current code creates a userValue dictionary but doesn't add it to the userArray before saving. Let's correct that to ensure new entries are stored properly:
// Create the user info dictionary safely (no force unwrap needed) let userValue: [String: String] = [ "name": self.nameLbl.text ?? "", "lastName": self.lastNameLbl.text ?? "", "city": cityLbl.text ?? "" ] // Fetch existing array from UserDefaults (or initialize empty if none exists) var userArray = UserDefaults.standard.array(forKey: "userInfo") as? [[String: String]] ?? [] // Add the new user entry to the array userArray.append(userValue) // Save the updated array back to UserDefaults UserDefaults.standard.set(userArray, forKey: "userInfo") // Optional: For pre-iOS 10 versions, you can call synchronize (not required for modern iOS) // UserDefaults.standard.synchronize()
Note: Avoid using as! here—it can cause crashes if type casting fails. Explicitly defining the dictionary type [String: String] is safer.
3. Complete the UITableView Display in Second ViewController
To fully show the userInfo array in your table view, you need to load the data from UserDefaults and implement the required UITableView DataSource methods. Here's the full implementation:
class SecondViewController: UIViewController, UITableViewDataSource { var userInfo = [[String:String]]() @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Load saved data from UserDefaults if let savedUsers = UserDefaults.standard.array(forKey: "userInfo") as? [[String: String]] { userInfo = savedUsers } // Set the table view's data source tableView.dataSource = self // Register a default cell (replace with your custom cell if needed) tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UserInfoCell") } // MARK: - UITableView DataSource Methods func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return userInfo.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "UserInfoCell", for: indexPath) let currentUser = userInfo[indexPath.row] // Format cell content to display user info (customize this to your needs) cell.textLabel?.text = "\(currentUser["name"] ?? "") \(currentUser["lastName"] ?? "")" cell.detailTextLabel?.text = "City: \(currentUser["city"] ?? "")" return cell } }
If you're using a custom UITableViewCell, replace the default cell registration and configure your custom cell's outlets instead of using textLabel/detailTextLabel.
内容的提问来源于stack exchange,提问作者Nazar

