swift:如何在另一个视图控制器中访问一个变量?

时间:2016-04-07 06:35:36

标签: ios swift delegates

我有ViewController.swift,在这个视图控制器里面我有

 let array = NSUserDefaults.standardUserDefaults().objectForKey("\(login)") as! NSArray

let name = array[2]

我想获取3个数组元素并在ProfileViewController.swift中使用它

我应该做什么?

2 个答案:

答案 0 :(得分:2)

使用prepareForSegue方法 -

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "SegueToProfileView" {
        //Replace "SegueToProfileView" with your segue identifier
        let x = segue.destinationViewController as! ProfileViewController
        x.arrayReceived = array

    }  
}

Inside ProfileViewController

var arrayReceived: [String]!

每当执行segue时,arrayReceived将包含您的数组

let viewController = self.storyboard.instantiateViewControllerWithIdentifier("profileView") as ProdileViewController
viewController.arrayReceived = array

希望这有帮助

答案 1 :(得分:0)

类永恒{

class func setObject(value: AnyObject!, forKey defaultName: String!) {
    let defaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()
    defaults.setObject(value, forKey:defaultName)
    defaults.synchronize()
}

class func objectForKey(defaultName: String!) -> AnyObject! {
    let defaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()

    return defaults.objectForKey(defaultName)
}

}

用法

Eternal.setObject("断开我。我宁愿什么都不要",forKey:" Bishop") Eternal.objectForKey("毕晓普&#34)