1

我有一个 viewControllerController和一个 view view A。还ViewA包含一个按钮。通常,我们在单击按钮时调用同一类中的函数来执行。但是我希望controller在单击按钮时执行一个方法。

以下是我制定的两种方法:

//method 1 
//UIView A
-(id)initWithSelector:(SEL)callbackInB withDelegate:(id)delagateB
{
    self = [super init];
    if (self)
    {
         delegate = delegateB;
         myCB = callbackInB;
    }
    return self;
}
//somewhere in UIView A
[btn addTarget:delegate action:myCB forControlEvents:UIControlEventTouchUpInside];

这很好用。但是如果我使用第二种方法,它会显示“执行选择器可能会泄漏,因为选择器功能未知”。

//method 2
//somewhere in UIView A 
[btn addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];


-(void)btnPressed:(id)sender
{

    if([delegate respondsToSelector:myCB])
        [delegate performSelector:myCB];

}
4

1 回答 1

1

块是这个问题的答案:

B类

@property (copy, nonatomic) void (^myBlock)(void);

 -(id)initWithMyBlock:(void(^)(void))block
 {
    self = [super init];
    if (self)
    {
         self.myBlock = block;
    }
     return self;
 }

[btn addTarget:delegate action:@selector(btnPressed) forControlEvents:UIControlEventTouchUpInside];

- (void)btnPressed {
  if (_myBlock) {
    _myBlock();
  }
}

只需注意保留周期

于 2013-04-24T12:38:26.117 回答