Ios ViewDidLoad()处的实例变量重置为nil
我有一个从Ios ViewDidLoad()处的实例变量重置为nil,ios,swift,reset,instance-variables,Ios,Swift,Reset,Instance Variables,我有一个从UIViewController继承的对象。在这个对象中,我有一个包含用户配置文件的实例变量(类型:UserProfile)。我在ViewDidLoad()之前设置这个变量,但一旦我输入它,这个变量就会重置为nil 这是我的密码: class MapViewController: UIViewController { var userProfile: UserProfile! required init(coder: NSCoder) {
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
您可以在此处创建MapViewController的新实例:
self.mapViewController = MapViewController()
self.mapViewController?.setProfile(self.userProfile)
//The controller is pushed through the storyboard
您应该使用segue的destinationcontroller:
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!)
{
if (segue.identifier == "showSecondViewController")
{
var second = segue.destinationViewController as SecondViewController
second.setProfile(...)
}
}
事实上,我正在处理两个不同的例子。。。不习惯故事板,我要检查一下这个故事。谢谢你的快速回答!是否可以这样做:
let storyboard=UIStoryboard(name:“Main”,bundle:nil)self.mapViewController=storyboard.instanceeviewcontrollerwhiteIdentifier(“mapViewController”)作为mapViewController
当然可以,但您没有与segue连接的实例相同。因此,您也可以创建一个新实例。