问题
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