LEVIS OGCPAS
LEVIS OGCPAS

Reputation: 229

fatal error on calling function from another class

I'm having trouble on calling the function from a different class. I have this:

class ViewController: UIViewController {

    func addToOrder(orderNumber:String) {

        orderCount.text = orderNumber

    }

}

Now in my other class:

class TableViewController: UITableViewController {

   func addToOrder(button: UIButton) {


      ViewController().addToOrder("100")

      //I also tried

       var menu = ViewController()
       menu.addToOrder("100")

     }

}

I'm getting error on this line

    orderCount.text = orderNumber

with this error:

fatal error: unexpectedly found nil while unwrapping an Optional value

Upvotes: 0

Views: 462

Answers (2)

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

You can use NSNotificationCenter for that.

Follow this step:

first of all add this in your first viewController where you want to update text:

override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "refreshTable:", name: "refresh", object: nil)

}

Which will add an observer when your load your first view and also add this helper method which will call when you come back to this view:

func refreshTable(notification: NSNotification) {
    let orderDetail = NSUserDefaults.standardUserDefaults().integerForKey("order")  //this will read your integer which you will save on second view.
    orderCount.text = "\(orderDetail)"

}

In your next view add this code when you are coming back to previous view.

@IBAction func goBack(sender: AnyObject) {
    //store your int here
    NSUserDefaults.standardUserDefaults().setInteger(100, forKey: "order")
    //send notification to first view.
    NSNotificationCenter.defaultCenter().postNotificationName("refresh", object: nil, userInfo: nil)
    self.dismissViewControllerAnimated(true, completion: nil)
}

Hope this will help.

Upvotes: 1

knutigro
knutigro

Reputation: 1092

It's orderCount (which probably is a UILabel) which is nil at initialization-time. If this is a IBOutlet created in a storyboard, you will need to store your text as a separate property, and set the text of your Label to this property in your ´viewDidLoad´ method

Upvotes: 0

Related Questions