0

我正在使用这篇文章UIBlockButton中的代码:

typedef void (^ActionBlock)();

@interface UIBlockButton : UIButton {
  ActionBlock _actionBlock;
}

-(void) handleControlEvent:(UIControlEvents)event 
                 withBlock:(ActionBlock) action;

@implementation UIBlockButton

-(void) handleControlEvent:(UIControlEvents)event 
                 withBlock:(ActionBlock) action
{
  _actionBlock = Block_copy(action);
  [self addTarget:self action:@selector(callActionBlock:) forControlEvents:event];
}

-(void) callActionBlock:(id)sender{
  _actionBlock();
}

-(void) dealloc{
  Block_release(_actionBlock);
  [super dealloc];
}
@end

但是我将代码更改为 ARC 下,如何更改代码以确保一切正常?

4

1 回答 1

3

标题:

@interface UIBlockButton : UIButton

- (void) handleControlEvent: (UIControlEvents) event withBlock: (dispatch_block_t) action;

@end

执行:

@interface UIBlockButton ()
@property(copy) dispatch_block_t actionBlock;
@end

@implementation UIBlockButton
@synthesize actionBlock;

- (void) handleControlEvent: (UIControlEvents) event withBlock: (dispatch_block_t) action
{
    [self setActionBlock:action];
    [self addTarget:self action:@selector(callActionBlock:) forControlEvents:event];
}

- (void) callActionBlock: (id) sender
{
    if (actionBlock) actionBlock();
}

@end

但请注意,多次调用handleControlEvent:withBlock:将覆盖您的块,使用此实现,您不能对不同的事件有不同的操作。此外,您可能应该为该类使用不同的前缀,而不是UI防止与 Apple 代码的潜在冲突。

于 2012-07-12T09:58:13.177 回答