Swift中的自定义UITableViewCell委托模式
我在Swift + Objective-C问题中遇到了一个奇怪的问题。
我正在使用swift实现一个UITableView和一个带委托的自定义单元格,但是只要我的UITableViewController将我的单元委托分配给self,就会导致我的应用程序和Xcode崩溃。 是的每次我崩溃我的应用程序,Xcode崩溃,无论如何,但这是另一个问题。
这是我单元格的一部分
enum NewsCellActionType: Int { case Vote = 0 case Comments case Time } protocol NewsCellDelegate { func newsCellDidSelectButton(cell: NewsCell, actionType: NewsCellActionType) } class NewsCell: UITableViewCell { var cellDelegate: NewsCellDelegate? func selectedAction(action: NewsCellActionType) { self.cellDelegate?.newsCellDidSelectButton(self, actionType: action) } }
这是我在UIViewController中设置委托的地方
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { var cell = tableView.dequeueReusableCellWithIdentifier(NewsCellsId) as NewsCell if cell == nil { cell = NewsCell(style: UITableViewCellStyle.Default, reuseIdentifier: NewsCellsId) } cell.post = self.posts[indexPath.row] as HNPost cell.cellDelegate = self return cell }
它崩溃在行cell.cellDelegate = self,我不知道为什么。 这是当前DP中的错误,还是我做错了?
我尝试在协议上使用我的委托var + @objc标签上的弱,但是当我使用纯粹的Swift枚举时,我不能这样做。 但我需要它吗?
谢谢!
我需要进行两项更改才能使代码正常工作
1.替换as?
在tableView.dequeueReusableCellWithIdentifier
之后
(有关详细信息,请参阅Swift中的UITableView )
第一次更改不需要因为单元格不能nil
(故事板确保它)。 我已经错误地构建了代码。
2.将NewsCellDelegate
添加到NewsCellDelegate
@class_protocol protocol NewsCellDelegate {
我不确定为什么应用程序崩溃没有它,我认为这是一个错误。 但是, @class_protocol
都应该使用@class_protocol
,因为我们应该将cellDelegate
声明为weak
,而没有@class_protocol
我们不能这样做。
weak var cellDelegate: NewsCellDelegate?
不幸的是,添加weak
会使应用程序在使用委托时崩溃。
代码中存在大量内存泄漏,从库开始,该库是用ARC编写的,但它被设置为MRC。
你在NewsCell
中的关闭正在捕获self
,创建保留周期(以及随后泄露的细胞)。
我无法找到崩溃的原因,但我很确定这是编译器/运行时的一个错误,因为它不仅崩溃应用程序,而且Xcode和3次甚至崩溃了我的系统。
我在这里发布了答案 。
目前,如果委托应该是Objective-C类的Object(如UITableViewController),则必须使用@objc显式标记协议:
@objc protocol SwiftProtocol
这将实现与Objective-C的互操作
protocol NewsCellDelegate:class {func newsCellDidSelectButton(cell:NewsCell,actionType:NewsCellActionType)}
你错过了一个“class级”