如何使用ARC制作UIBlockButton?

时间:2012-07-12 09:47:12

标签: ios uibutton objective-c-blocks

我正在使用this post中的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下,如何更改代码以确保一切正常?

1 个答案:

答案 0 :(得分: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的代码发生潜在冲突。