[英]Is a UITableViewCell and its outlets initialized after `dequeueReusableCellWithIdentifier`?
Is it save to access an outlet of a custom UITableViewCell
right after instantiating it with dequeueReusableCellWithIdentifier
? 使用
dequeueReusableCellWithIdentifier
实例化自定义UITableViewCell
的出口后,是否可以保存访问它?
Eg 例如
class MyCell: UITableViewCell {
@IBOutlet weak var myImageView: UIImageView!
var image: UIImage?
override func awakeFromNib() {
update()
}
func update() {
myImageView.image = image
}
}
class MyViewController: UIView() {
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MyCellIdentifier") as! MyCell
cell.image = UIImage(...)
cell.update()
}
}
I have used this implementation a lot but very rarely (<0.001%) I get a crash report pointing to line myImageView.image = image
. 我已经使用了很多这种实现,但是很少(<0.001%)我收到崩溃报告,指向
myImageView.image = image
。
UPDATE: So far the crashes have been observed only for one specific implementation where 1 outlet is linked to many UIImageView()
in custom cells because they share the same class. 更新:到目前为止,仅在一种特定的实现中观察到了崩溃,其中一个插座链接到自定义单元格中的许多
UIImageView()
,因为它们共享同一类。
The simple method dequeueReusableCellWithIdentifier:
returns an optional which is not safe. 简单的方法
dequeueReusableCellWithIdentifier:
返回一个不安全的可选方法。
Use this method instead which is safe because it returns an non-optional cell 请改用此方法,因为它返回一个非可选单元格,因此是安全的
let cell = tableView.dequeueReusableCellWithIdentifier("MyCellIdentifier",
forIndexPath: indexPath) as! MyCell
Since the image
property of an UIImageView
object can be nil
it's recommended to declare related UIImage
properties as optional ( ?
) rather than implicit unwrapped optional ( !
) without the default initializer ( ()
) 由于
UIImageView
对象的image
属性可以为nil
因此建议将相关的UIImage
属性声明为可选( ?
),而不是在没有默认初始值设定项( ()
)的情况下隐式展开的可选( !
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.