簡體   English   中英

對於addTarget:action:forControlEvents的addTarget指針行為感到困惑:

[英]Confused about addTarget pointer behavior for addTarget:action:forControlEvents:

我有一個帶有委托屬性的UIView子類。 在init方法中,我設置

self.delegate = nil. 

該視圖還具有一個按鈕,因此在init方法中,我還將按鈕的目標設置為self.delegate,即為nil:

[myButton addTarget:self.delegate action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside]

在設置我的UIView子類的UIViewController中,我調用UIView中的方法,該方法將UIView的self.delegate設置為UIViewController。 當我單擊按鈕時,目標更改似乎已得到反映。

我想知道這將如何工作,因為我的理解是addTarget:action:forControlEvents將id作為目標,並且指針應該在Obj-C中按值傳遞。 因此,我對為什么已經調用addTarget方法后更新原始零值指針感到非常困惑。

正確的方法是為您的視圖聲明一個協議,該協議將委托按鈕的點擊操作,即

YourView.h

@class YourView;
@protocol YourViewDelegate
@optional
- (void)customView:(YourView *)view didSelectButton:(id)button;

@end

@interface YourView : UIView

//...
@property (weak, nonatomic) id <YourViewDelegate> delegate;

@end

YourView.m

@interface YourView()

@end

@implementation

- (id)init
{
   if (self = [super init]) {
      //...
      [self setup];
   }

   return self;
}

- (void)awakeFromNib
{
    //...
    // setup logic when this view created from storyboard
    [self setup];
}

- (void)setup
{
    [myButton addTarget:self 
                 action:@selector(buttonTapped:)     
       forControlEvents:UIControlEventTouchUpInside];
}

- (void)buttonTapped:(id)sender
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(customVIew:didSelectButton)] {
       [self.delegate customView:self didSelectButton:sender];
    }
}
@end

然后,在視圖控制器中實現YourViewDelegate類別:

@interface YourViewController() 

//...
@end

@implementation

- (void)viewDidLoad
{ 
    [super viewDidLoad];

    //...
    self.yourView.delegate = self;
}

//...
- (void)customView:(YourView *)view didSelectButton:(id)button
{
    //do your stuff
}

@end

Objective-C使用Dynamic binding 要調用的方法是在運行時而不是在編譯時確定的。 這就是為什么它也稱為后期綁定。

參考鏈接-https://developer.apple.com/library/ios/documentation/general/conceptual/DevPedia-CocoaCore/DynamicBinding.html

因此,將在運行時定義什么是委托以及將調用哪個方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM