当我们可以将所有内容转储到 awakeFromNib 中时,为什么还要使用 init(coder)?
Why should we use init(coder) when we can just dump everything inside awakeFromNib?
我读了What exactly is init coder aDecoder?
但这并不能回答为什么不将所有内容都放在 awakeFromNib
中而忘记使用 init(coder aCoder : NSCoder)
?
在已接受答案的评论中,Fattie 说:
"sometimes you can't do that". You typically can but not always
谁能对此提供更多解释?
如果 lets
需要在 init
中初始化,则必须使用它而不是 awakeFromNib
。
这样做可以避免隐式解包可选值。
编辑:
如果你想让你的 class 有属性,你可以做
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
始终被初始化,它需要在 class 的 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。
我读了What exactly is init coder aDecoder?
但这并不能回答为什么不将所有内容都放在 awakeFromNib
中而忘记使用 init(coder aCoder : NSCoder)
?
在已接受答案的评论中,Fattie 说:
"sometimes you can't do that". You typically can but not always
谁能对此提供更多解释?
如果 lets
需要在 init
中初始化,则必须使用它而不是 awakeFromNib
。
这样做可以避免隐式解包可选值。
编辑:
如果你想让你的 class 有属性,你可以做
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
始终被初始化,它需要在 class 的 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。