What I am trying to do in general:
1. Generate a table with all registered users (stored in core data).
2. Then allow the user to select a registered-user by pressing on a row.
3. When user selects a row, a new page opens with detailed user info.
I am trying to solve this by:
1. First storing the UserName from the given cell into "UserDefaults.standard".
2. Then on the second page, accessing the stored UserName from "UserDefaults.standard" and using that dynamic value to retrieve Core Data for more detailed user information.
Problems:
I am certain that the data that is passed into "UserDefaults.standard" is the full table and not data from a specific cell. I have seen this by using "Print()", is actually show all of the rows instead of only the one row that is selected.
So the UserName that is then generated into the second page is a random row that is further down (see picture).
public class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var userNameobject : [NSManagedObject] = []
@IBAction func pushTwo(_ sender: Any) {
}
@IBOutlet weak var usersList: UITableView!
override public func viewDidLoad() {
super.viewDidLoad()
usersList.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return }
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Users")
do {
userNameobject = try managedContext.fetch(fetchRequest)
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
}
public func tableView(_ usersList: UITableView, numberOfRowsInSection section: Int) -> Int {
return userNameobject.count
}
public func tableView(_ usersList: UITableView, cellForRowAt indexPath: IndexPath)
-> UITableViewCell {
let person = userNameobject[indexPath.row]
let cell = usersList.dequeueReusableCell(withIdentifier: "CellTwo", for: indexPath) as UITableViewCell
cell.textLabel?.text = person.value(forKeyPath: "userName") as? String
// STORE USERNAME
let defaults = UserDefaults.standard
defaults.set(person.value(forKeyPath: "userName"), forKey: "userNameDefault")
return cell
}
}
public func tableView(_ userList: UITableView, didSelectRowAt indexPath: IndexPath)
{
}