一個選項是設置按鈕彈起使用
[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
然後在你執行
MyController.m
- (IBAction)buttonTapped:(UIButton *)button
{
if ([self.delegate respondsToSelector:@selector(myController:buttonTapped:)]) {
[self.delegate myController:self buttonTapped:button];
}
}
在協議中定義的方法不是可有可無的,我可以代替做了(self.delegate)
檢查,以使確定它被設置而不是respondsToSelector
。
我使用了第一件事,因爲我從不關閉應用程序中的「目標」。不過,我非常感謝你給出反對的理由,因爲我的應用可能會發生變化。 – Jacksonkr