我有一个继承自UIViewController
的对象。在这个对象中,我有一个包含用户配置文件的实例变量(类型:UserProfile
)。我在ViewDidLoad()
之前设置了这个变量,但是一旦我输入它,变量就会重置为nil
......
这是我的代码:
class MapViewController: UIViewController {
var userProfile: UserProfile!
required init(coder: NSCoder) {
super.init(coder: coder)
}
override init() {
super.init()
}
override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
func setProfile(userProfile: UserProfile) {
self.userProfile = userProfile
//self.userProfile is OK
}
override func viewDidLoad() {
super.viewDidLoad()
self.userProfile is equal to nil....
}
}
以下是控制器的声明:
self.mapViewController = MapViewController()
self.mapViewController?.setProfile(self.userProfile)
//The controller is pushed through the storyboard
答案 0 :(得分:2)
在这里创建一个新的MapViewController实例:
self.mapViewController = MapViewController()
self.mapViewController?.setProfile(self.userProfile)
//The controller is pushed through the storyboard
您应该使用来自segue的目标控制器:
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!)
{
if (segue.identifier == "showSecondViewController")
{
var second = segue.destinationViewController as SecondViewController
second.setProfile(...)
}
}