Objective c UIButton在代码中设置触摸处理程序

Objective c UIButton在代码中设置触摸处理程序,objective-c,ios,Objective C,Ios,我想触摸ui按钮,让代码在不同于所有者的类中运行 我意识到我可以对按钮的所有者(ClassA)进行touchUpInside),然后调用我想要调用的ClassB内的方法,但是有什么方法可以加快这个过程吗 想法: 让ClassB成为ClassA->ui按钮的代表 将touchUpInside调用编程设置为使用ClassB中的函数 我不知道如何实现这两个想法:(非常感谢您的输入!一个选项是使用 [myButton addTarget:yourOtherClass action:@selector

我想触摸
ui按钮
,让代码在不同于所有者的类中运行

我意识到我可以对按钮的所有者(
ClassA
)进行
touchUpInside
),然后调用我想要调用的
ClassB
内的方法,但是有什么方法可以加快这个过程吗

想法:

  • ClassB
    成为
    ClassA->ui按钮的代表

  • touchUpInside
    调用编程设置为使用
    ClassB中的函数


我不知道如何实现这两个想法:(非常感谢您的输入!

一个选项是使用

[myButton addTarget:yourOtherClass action:@selector(mySelector:) forControlEvents:UIControlEventTouchUpInside];
但这有点危险,因为
target
未保留,因此您可以将消息发送到解除分配的对象

你可以建立一个协议

MyController.h

@protocol MyControllerDelegate
- (void)myController:(MyController *)controller buttonTapped:(UIButton *)button;
@end

@interface MyController : UIViewController

@property (nonatomic, assign) id <MyControllerDelegate> delegate;

- (IBAction)buttonTapped:(UIButton *)button;

@end

由于协议中定义的方法不是可选的,因此我可以检查
(self.delegate)
,以确保它已设置,而不是
respondsToSelector

,我使用了第一件事,因为我从未忽略“目标”但是,我非常感谢你给出反对使用它的理由,因为我的应用可能会改变。
MyController.m

- (IBAction)buttonTapped:(UIButton *)button
{
    if ([self.delegate respondsToSelector:@selector(myController:buttonTapped:)]) {
      [self.delegate myController:self buttonTapped:button];
    }
}