All IBOutlets become nil after switching to Xcode

2019-03-22 03:18发布

For instance, there is a property in a view controller

@IBOutlet weak var nameLabel: UILabel!

This property is nil inside viewWillAppear and viewDidLoad, so the app crashes at runtime.

It was working fine in Xcode 6 Beta 4. After I switched to Beta 5, it complained about the controller class does not implement its superclass's required members. So I added

required init(coder aDecoder: NSCoder!) {
  super.init(coder: aDecoder)
}

And that compiler error disappeared. However, the app crashes for unexpectedly found nil while unwrapping an Optional value because that nameLabel property is nil when I try to set its text.

I read through the release notes and could not figure out how to fix this issue.

标签: swift xcode6
2条回答
干净又极端
2楼-- · 2019-03-22 03:59

I was having the same issue in Beta5. It appears to be a problem where

init(nibName: nil, bundle: nil) 

is not mapping nil to the default nibName. When I changed to an explicit nibName then it worked. Specifically in my case, using the new ?? operator:

override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
   // beta5 workaround: replace nil with explicit name of xib file
   let nib = nibNameOrNil ?? "MyViewController"

   super.init(nibName: nib, bundle: nibBundleOrNil)

   // local initialization here
}

caused it to magically work again.

查看更多
孤傲高冷的网名
3楼-- · 2019-03-22 04:07

It's a temporary bug. The workaround turns out to be: Declare your view controller in such a way as to override name mangling, like this:

@objc(ViewController) ViewController : UIViewController { // or whatever its name is

See also: Are view controllers with nib files broken in ios 8 beta 5?

EDIT This bug is fixed in iOS 9 beta 4.

查看更多
登录 后发表回答