为什么这个变量不能在这个函数中打印?

时间:2016-10-15 18:39:45

标签: ios swift xcode swift3 xcode8

加载ViewController时,会打印正确的值。但是当尝试使用UIButton打印相同的值时,打印为reader = csv.reader(f, delimiter=',') for i in reader: try: ws.append(float(i)) except ValueError: ws.append(i) f.close()

的ViewController

nil

userEmail值是通过以下代码部分从LoginViewController传递的:

var userEmail: String?

func userLoggedIn(data: String) {

    userEmail = data //sent from delagate
    print(userEmail) // successfully printed
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "loginView" {
        let loginViewController: LoginViewController = segue.destination as! LoginViewController
        loginViewController.delegate = self
    }
}

override func viewDidAppear(_ animated: Bool) {

   let isUserLoggedIn = UserDefaults.bool(UserDefaults.standard)(forKey: "isUserLoggedIn")

    if(!isUserLoggedIn) {
        self.performSegue(withIdentifier: "loginView", sender: self);
    }   
}

@IBAction func createCommunityTapped(_ sender: AnyObject) {

    let createCommunityController = self.storyboard?.instantiateViewController(withIdentifier: "CreateNewCommunity") as! CreateNewCommunity

    print ("now here ", userEmail) // prints nil
    createCommunityController.myEmail = userEmail
}

的AppDelegate:

if(returnValue != "error") {

     self.delegate?.userLoggedIn(data: userEmail! )                
     UserDefaults.set(UserDefaults.standard)(true, forKey: "isUserLoggedIn");

     let mainPage = self.storyboard?.instantiateViewController(withIdentifier: "ViewController")
     let mainPageNav = UINavigationController(rootViewController: mainPage!)
     let appDelegate = UIApplication.shared.delegate
     appDelegate?.window??.rootViewController = mainPageNav 

     self.dismiss(animated: true, completion: nil)                
}

1 个答案:

答案 0 :(得分:-1)

问题似乎在于您的登录视图控制器。您将userEmail传递给ViewController的第一个实例,然后创建ViewController的新实例并将其设置为根,从而释放第一个实例。第一步应该是删除此代码:

let mainPage = self.storyboard?.instantiateViewController(withIdentifier: "ViewController")
let mainPageNav = UINavigationController(rootViewController: mainPage!)
let appDelegate = UIApplication.shared.delegate
appDelegate?.window??.rootViewController = mainPageNav 

在AppDelegate中,您应该将根视图控制器设置为ViewController,并在用户未登录时以模态方式在其顶部显示LoginViewController。确保设置{{1委托给LoginViewController's。然后您的登录逻辑可以是:

ViewController