我读了What exactly is init coder aDecoder?
但这并没有回答为什么不把所有东西都放在 awakeFromNib
中而忘记使用 init(coder aCoder : NSCoder)
?
在已接受答案的评论中,Fattie 说:
"sometimes you can't do that". You typically can but not always
谁能对此提供更多解释?
最佳答案
如果您有 let
需要在 init
中初始化,则必须使用它而不是 awakeFromNib
。
这样做可以避免隐式解包可选值。
编辑:
如果你想让你的类有属性,你可以这样做
let a: String
或
var a: String! = nil // this is called an "implicitly unwrapped optional" -- it's the ! at the end of the type that makes it that.
第一个是可取的,因为它是安全的。在第二种情况下,您冒着在初始化之前访问 a
的风险。
但是,要确保 a
始终被初始化,它需要在类的 init
中获取它的值。
所以,
init(coder aCoder : NSCoder) {
a = "hello" // usually this is something more complex
// read in coder or whatever else you need to do
}
如果你没有一个 init,那么你就不能有一个稍后被初始化的 init。
关于ios - 当我们可以将所有内容转储到 awakeFromNib 中时,为什么还要使用 init(coder)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43124466/