addTarget可以安全使用吗?

时间:2015-08-13 06:00:08

标签: ios objective-c swift uitableview addtarget

我最近有点怀疑,在 cellForRowAtIndexPath 中使用addTarget()到UITableViewCell。我也很想知道从UITableViewCell监听按钮事件的最佳做法是什么。

当我看到我无法取消注册我添加到UITutton中的UIButton驻留的 addTarget 侦听器时,我的困惑就开始了:

cellForRowAtIndexPath 的代码:

cell.button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)

上面的代码注册了一个驻留在UITableViewCell中的UIButton的监听器,但我看不到取消注册它们的引用。我不确定这个过程是否是自动的(对于addTarget-mechanism),我还没有找到任何在Apple doc(至少我已经搜索过)中这样说的引用。

所以,我的问题是, addTarget 用于UITableViewCell按钮是否很好用?当视图控制器消失时,它们是否都取消注册?

或者,如果我使用addObserver会很好吗?

override func viewDidLoad()
{
        super.viewDidLoad()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "onCellButtonPressed:", name: "cellButtonPressed", object: nil)
}

func onCellButtonPressed(notification:NSNotification)
{
        if let sender = notification.object as? UIButton
        {
                ...
        }
}

在UITableViewCell代码中:

@IBAction func onButtonPressed(sender: AnyObject)
{
NSNotificationCenter.defaultCenter().postNotificationName("cellButtonPressed", object: sender)
}

对此有任何建议,将不胜感激。

1 个答案:

答案 0 :(得分:2)

不会保留传递给addTarget的目标。使用安全;您不需要“取消注册”(或删除)目标。这是控制操作的标准机制(如按钮按下),您应该使用它(与通知相对)。

相关问题