2012-07-12 16 views
0

我使用的UIBlockButton代碼this post如何用ARC製作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下,如何更改代碼,以確保一切正常?

回答

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代碼發生潛在衝突。

+0

感謝您編輯我的帖子,並很快重放我的問題。 – jeswang 2012-07-12 10:02:05

+0

'[self setActionBlock:action];'可以寫成'self.actionBlock = action;' – newacct 2012-07-12 22:14:43