Found nil when unwrapping optional value in core data - ios

I've been trying to address this issue for a few days and it seems I'm only going in circles.
I'm adding data to core data by tapping on tableView cells and then displaying the items on another tableView.
That works great, the problem is this:
When I click on the other table view rows, to be able to see the item with all the other values stored in core data, I get
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value on the showMeTheGoodiesTwo(entry: myCart) line
...Inside viewDidLoad. But I do not know why that's happening, as the entity is not empty.
Here's the code of the view controller where I want to display the item's details.
Hope somebody can give me a hand.
Cheers!
import UIKit
class productQuantityViewController: UIViewController {
var myCart: Cart!
#IBOutlet weak var productImage: UIImageView!
#IBOutlet weak var productNameLabel: UILabel!
#IBOutlet weak var productDescriptionLabel: UILabel!
#IBOutlet weak var productAmountLabel: UITextField!
#IBOutlet weak var minusButton: UIButton!
#IBOutlet weak var plusButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
productImage.layer.cornerRadius = 10
minusButton.layer.cornerRadius = minusButton.frame.size.width/2
plusButton.layer.cornerRadius = plusButton.frame.size.width/2
showMeTheGoodiesTwo(entry: myCart)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func showMeTheGoodiesTwo(entry: Cart) {
let name = entry.product
let quantity = entry.inventory
let description = entry.productDescription
let image = entry.productImage as Data?
let xNSNumber = quantity as NSNumber
productNameLabel!.text = name
productDescriptionLabel!.text = description
productAmountLabel!.text = xNSNumber.stringValue
productImage!.image = UIImage(data:image!)
print(productNameLabel.text as Any)
}
}

You need to change
var myCart: Cart!
To
var myCart: Cart?
? is use to make it optional.
And in viewDidLoad use
if (myCart != nil){
showMeTheGoodiesTwo(entry: myCart)
} else {
//do something.
}
instead of
showMeTheGoodiesTwo(entry: myCart)

Related

Geting a fatal "error: unexpectedly found nil while unwrapping an Optional value" when chaging value of label on button press

I keep getting nil value when I press button.
import UIKit
class ViewController: UIViewController {
//MARK: Properties
#IBOutlet weak var txt_vrednost: UITextField!
#IBOutlet weak var btn_dodaj: UIButton!
#IBOutlet weak var lbl_stanje: UILabel!
var novcanik = 0.0
//MARK: Acttion
#IBAction func btn_dodaj_pressed(_ sender: Any) {
let values = Double(txt_vrednost.text!)
novcanik = novcanik + values!
lbl_stanje.text=String(novcanik)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
First of all make sure all your outlets are connected with storyboard. You are using force unwrap everywhere, which is causing crash :
import UIKit
class ViewController: UIViewController {
//MARK: Properties
#IBOutlet weak var txt_vrednost: UITextField!
#IBOutlet weak var btn_dodaj: UIButton!
#IBOutlet weak var lbl_stanje: UILabel!
var novcanik = 0.0
//MARK: Action
#IBAction func btn_dodaj_pressed(_ sender: Any) {
guard let values = txt_vrednost.text as? Double else {
print("not convertible")
return
}
novcanik = novcanik + values
lbl_stanje.text = "\(novcanik)"
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}

Why viewWithTag is returning nil

activite1Label as the tag 1
class StatsViewController: UIViewController {
#IBOutlet weak var activite1Label: UILabel!
#IBOutlet weak var activite2Label: UILabel!
#IBOutlet weak var activite3Label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
activite1Label.text = activite[0]
activite2Label.text = activite[1]
activite3Label.text = activite[2]
miseAjourTotal()
}
func miseAjourTotal() {
let leLabel = view.viewWithTag(1) as! UILabel
print("leLabel: \(leLabel.text)")
}
}
Nothing in your code tells that the label has the tag 1. You should go to your storyboard and check if the label does have tag 1 or set the tag programmatically

Swift Thread 1:EXC_BREAKPOINT error

I'm a newbie to swift and for now it's a pain in the a$$ to code.
I'm trying to make a very simple app where the user enters a number to a textfield
and then when a button is clicked it shows the number + 1 in a label.
I always get this error:
Thread 1:EXC_BREAKPOINT (code=1, subcode=0x1002c11ec)
This is my code:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var tav: UITextField!
#IBOutlet weak var fogy: UITextField!
#IBOutlet weak var ar: UITextField!
#IBOutlet weak var eredmeny: UILabel!
#IBOutlet weak var szamolasBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func szamol(_ sender: Any) {
let number = Int(tav.text!)! + 1
eredmeny.text = String(describing: number)
}
}
I ran your code and it works fine if an integer in entered in the textfield. But if you enter any character other than a string then the app crashes because Int(tav.text!)! returns nil and adding 1 to nil. Check for nil first and then add something to it.

Variable retaining old value when trying to reset it

I'm pretty new to Swift and programming, so this may seem pretty basic, but I haven't been able to locate an answer on StackOverflow or Google while trying to solve this issue today.
I'm create a basic life counter app for fun, but I'm having some trouble when I'm trying to reset the user's life totals. I'm able to add and subtract totals from the starting value, but when I run reset it the initial value is staying in memory.
For example, if player one has 9 life and player 2 has 0, if I hit the reset button both totals will show 10 (the default), however, if I subtract 1 from player 1 it will show 8 and if I added 1 to player 2 it would show 1 instead of 11.
I guess I need to pass the value from reset somehow or just put the default variable somewhere else? Any help is appreciated. Thanks.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var playerOneAdd: UIButton!
#IBOutlet weak var playerOneMinus: UIButton!
#IBOutlet weak var playerOneLife: UILabel!
#IBOutlet weak var playerTwoMinus: UIButton!
#IBOutlet weak var playerTwoPlus: UIButton!
#IBOutlet weak var playerTwoLife: UILabel!
#IBOutlet weak var resetButton: UIButton!
var playerOne = 10
var playerTwo = 10
override func viewDidLoad() {
super.viewDidLoad()
playerOneLife.transform = CGAffineTransformMakeRotation(3.14)
}
#IBAction func PlayerOnePlusButton(sender: AnyObject) {
++playerOne
playerOneLife.text = String(playerOne)
}
#IBAction func playerOneMinusButton(sender: AnyObject) {
--playerOne
playerOneLife.text = String(playerOne)
}
#IBAction func playerTwoMinusButton(sender: AnyObject) {
--playerTwo
playerTwoLife.text = String(playerTwo)
}
#IBAction func playerTwoPlusButton(sender: AnyObject) {
++playerTwo
playerTwoLife.text = String(playerTwo)
}
#IBAction func resetPressed(sender: AnyObject) {
var playerOne = 10
var playerTwo = 10
playerOneLife.text = String(playerOne)
playerTwoLife.text = String(playerTwo)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
When you call var again, you re-define the variable. You should just set it equal.
playerOne = 10
playerTwo = 10
You need to remove the var keyword in resetPressed:
#IBAction func resetPressed(sender: AnyObject) {
playerOne = 10
playerTwo = 10
playerOneLife.text = String(playerOne)
playerTwoLife.text = String(playerTwo)
}
The var keyword defines a new variable. Since the variables are declared inside of a function, they are local variables and they override the instance variables. Local variables are local to a function, so the overridden variables aren't accessed in the other functions.

App crashing when adding second stepper

I have successfully got a step updating the values of a Text Field and now i am trying to add a second stepper but the app is now crashing.
#IBOutlet weak var propertyTypeField: UITextField!
#IBOutlet weak var insuranceTypeField: UITextField!
#IBOutlet weak var bedroomField: UITextField!
#IBOutlet weak var bathroomField: UITextField!
#IBOutlet weak var doYouOwnPropertyField: UITextField!
#IBOutlet weak var propertyYearField: UITextField!
#IBOutlet weak var bathroomStepper: UIStepper!
#IBOutlet weak var bedroomStepper: UIStepper!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(red: 0xE1/255, green: 0xE1/255, blue: 0xE1/255, alpha: 1.0)
//Bedroom stepper setup
bedroomField.text = "\(Int(bedroomStepper.value))"
bedroomStepper.addTarget(self, action: "stepperValueDidChange:", forControlEvents: .ValueChanged)
//Bathroom stepper setup
bathroomField.text = "\(Int(bathroomStepper.value))"
bathroomStepper.addTarget(self, action: "stepperValueDidChange:", forControlEvents: .ValueChanged)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func viewTapped(sender : AnyObject) {
propertyTypeField.resignFirstResponder()
insuranceTypeField.resignFirstResponder()
bedroomField.resignFirstResponder()
bathroomField.resignFirstResponder()
doYouOwnPropertyField.resignFirstResponder()
propertyYearField.resignFirstResponder()
}
func stepperValueDidChange(stepper: UIStepper) {
let bedroomStepperMapping: [UIStepper: UITextField] = [bedroomStepper: bedroomField]
if !(bedroomField.text == ""){
bedroomStepperMapping[stepper]!.text = "\(Int(stepper.value))"}
let bathroomStepperMapping: [UIStepper: UITextField] = [bathroomStepper: bathroomField]
if !(bathroomField.text == ""){
bathroomStepperMapping[stepper]!.text = "\(Int(stepper.value))"}
}
This is the whole code i am using.
The error i am getting is
fatal error: unexpectedly found nil while unwrapping an Optional value
Hope someone can help.
Thanks
By using ! bedroomStepperMapping[stepper]!.text your telling the compiler there will be a value there. As there is not one apparently you are getting the error. Check if the value is nil before unwrapping it
To check for nil in the line you say is the issue
if !(bedroomField.text == ""){
//Ok to unwrap object
}
While if you are using the optional value first check if value exist if not then there must not b null so do it as
if let bedFeild = Int(stepper.value) {
bedroomStepperMapping[stepper].text = bedFeild
}
Now there will be no crash if the value exist then value will be assigned to it else no without any crash
func stepperValueDidChange(stepper: UIStepper) {
if bedroomStepper == stepper{
bedroomField.text = "\(Int(stepper.value))"}
if bathroomStepper == stepper{
bathroomField.text = "\(Int(stepper.value))"}
}
}

Resources