Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Ektoras Drandakis
29,580 PointsXcode: unexpectedly found nil while unwrapping option value in label
When a new user registers in want to assign the username text in a label in another viewcontroller but i get a fatal error crash. Here is my code:
@IBAction func signupBtn(sender: UIButton) {
var email = self.emailField.text
var password = self.passwordField.text
var username = self.usernameField.text
self.actInd.startAnimating()
var newUser = PFUser()
newUser.email = email
newUser.password = password
newUser.username = username
userVC.usernameLbl.text = username // Here i get the crash!
newUser.signUpInBackgroundWithBlock({ (succeed, error) -> Void in
self.actInd.stopAnimating()
if((error) != nil) {
var alert = UIAlertView(title: "Error", message: "\(error)", delegate: self, cancelButtonTitle: "Ok")
alert.show()
} else {
// var alert = UIAlertView(title: "Success", message: "Signed Up", delegate: self, cancelButtonTitle: "Ok")
// alert.show()
self.change_screen()
}
})
}
1 Answer
Alvin Abia
Courses Plus Student 23,034 PointsI suspect that your crash is related to the fact that your username variable is contained only within the signupBtn func. By trying to set the text value of a label of another view controller to this variable, it will cause an error as the value of username that it's trying to access is out of that other view controller's scope. Here's two ways you could resolve this:
1) Move your username variable to outside the function so it's a member variable of the actual class whose function this is (so it would be a property of your initial view controller) and can be accessed outside of the sign up function. Then you could use username's value in prepareForSegue when setting the usernameLbl text value in userVC.
2) Log in the new user on successful signup so that after a user successfully signs up and logs in with Parse, you can access their username globally using PFUser's currentUser class method. Then in your userVC you can set your label like this:
usernameLbl.text = PFUser.currentUser().username
Hope this resolves your issue!
Ektoras Drandakis
29,580 PointsEktoras Drandakis
29,580 PointsYes this worked!
Thank you!