当我想在这样的按钮中调用警报时,我有一个方便的类:
- (IBAction)test:(id)sender {
[MyAlertView showWithTitle:@"test" withCallBackBlock:^(int value){
NSLog(@"Button Pressed %i", value);
}];
}
课程非常简单:
@implementation MyAlertView
@synthesize callBackBlock = _callBackBlock, internalCallBackBlock = _internalCallBackBlock;
-(void)showWithTitle:(NSString *)title withCallBackBlock:(CallBackBlock )callBackBlock internalCallBackBlock:(CallBackBlock )internalCallBackBlock{
self.callBackBlock = callBackBlock;
self.internalCallBackBlock = internalCallBackBlock;
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:title delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK" , nil];
[alertView show];
[alertView autorelease];
});
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (_callBackBlock) {
_callBackBlock(buttonIndex);
}
if (_internalCallBackBlock) {
_internalCallBackBlock(buttonIndex);
}
}
-(void)dealloc{
Block_release(_callBackBlock);
Block_release(_internalCallBackBlock);
[super dealloc];
}
+(void)showWithTitle:(NSString *)title withCallBackBlock:(CallBackBlock )callBackBlock{
__block MyAlertView *alert = [[MyAlertView alloc]init];
[alert showWithTitle:title withCallBackBlock:callBackBlock internalCallBackBlock:^(int value){
[alert autorelease];
}];
}
@end
我已经在模拟器上对其进行了分析,它显示没有泄漏,没有僵尸。现在,当我更改为 ARC 时,每次单击测试按钮时程序都会崩溃,即使我将所有内容都视为强大。我猜那是因为我没有持有 alertView 变量。
怎么能用 ARC 做这样的便利课?
附加 .h 文件:
#import <Foundation/Foundation.h>
typedef void(^CallBackBlock)(int value);
@interface MyAlertView : NSObject<UIAlertViewDelegate>
@property (copy) CallBackBlock callBackBlock, internalCallBackBlock;
+(void)showWithTitle:(NSString *)title withCallBackBlock:(CallBackBlock )callBackBlock;
@end