简体   繁体   中英

Swift3.0 I want to get object of AppDelegate

I wanna get object of AppDelegate. This program can build but it will stop running with lldb error.

Maybe the problem is the dirrerence of Swift2.0 and 3.0. My textbook is for swift2.0 but I am using xcode8.0 and Swift3.0.

Error is here.

let ap = UIApplication.shared.delegate as! AppDelegate

I used this page for fixing.

How do I get a reference to the app delegate in Swift?

import UIKit

class FirstViewController: UIViewController {

@IBOutlet weak var dataTextField: UITextField!


let ap = UIApplication.shared.delegate as! AppDelegate


override func viewWillAppear(_ animated: Bool) {
    dataTextField.text = String(ap.cmValue)
}


@IBAction func tapInpu() {

    dataTextField.resignFirstResponder()
    if let text = dataTextField.text{

        if let cmValue = Double(text){
        ap.cmValue = cmValue
        }
    }
}

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.
}


}

If you remove ap initialization and ap.cmValue = cmValue , does it works ?

If it does work check your outlet referencing in your storyboard you may have old non existent references

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM