Reputation: 23
I am working on Swift, I've got an error in tableview's didSelectRowAtIndexPath method. I want to pass a value to another view controller i.e 'secondViewController'. Here EmployeesId is an Array. The relevant code is as follows:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var view: Dashboard = self.storyboard?.instantiateViewControllerWithIdentifier("Dashboard") as Dashboard
self.navigationController?.pushViewController(view, animated: true)
secondViewController.UserId = employeesId[indexPath.item] //getting an error here.
}
But I am getting this Error: fatal error: unexpectedly found nil while unwrapping an Optional value.
Any help will be appreciated.
Upvotes: 1
Views: 24719
Reputation: 2789
Here's a general solution with two assumptions. First, UserId is not a UILabel. Second, you meant to use view
which was instantiated in the second line, instead of using secondViewController
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var view: Dashboard = self.storyboard?.instantiateViewControllerWithIdentifier("Dashboard") as Dashboard
view.userId = employeesId[indexPath.row]
self.navigationController?.pushViewController(view, animated: true)
}
Here's what Dashboard looks like:
class Dashboard: UIViewController {
var userId: String!
@IBOutlet var userIDLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
userIDLabel.text = UserId
}
...
}
Upvotes: 8
Reputation: 5053
We can pass value using "struct" in swift 3
Create a class in the swift file created like bellow
class StructOperation {
struct glovalVariable {
static var userName = String();
}
}
Assing value to "static var userName" variable of " struct glovalVariable" in "StructOperation" class from First View Controller like
@IBAction func btnSend(_ sender: Any) {
StructOperation.glovalVariable.userName = "Enamul Haque";
//Code Move to Sencon View Controller
}
In destination view controller get value like bellow
var username = StructOperation.glovalVariable.userName;
Upvotes: 4
Reputation: 16793
is UserId(strong, nonatomic)
in the secondViewController?
If it is weak, it sent trash on the fly. You have to make it strong.
Upvotes: 0