How to make UIBlockButton suit with ARC?

我怕爱的太早我们不能终老 提交于 2019-12-25 01:39:54

问题


I am using the UIBlockButton code from this post:

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

but I changed my code to under ARC, how to change the code to make sure everything works well?


回答1:


Header:

@interface UIBlockButton : UIButton

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

@end

Implementation:

@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

But note that multiple calls to handleControlEvent:withBlock: will overwrite your block, you can’t have different actions for different events with this implementation. Also, you should probably use a different prefix for the class instead of UI to prevent potential clashes with Apple’s code.



来源:https://stackoverflow.com/questions/11449194/how-to-make-uiblockbutton-suit-with-arc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!