0

当我想在这样的按钮中调用警报时,我有一个方便的类:

- (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
4

1 回答 1

0

你是对的:问题是UIAlertView创建的 in showWithTitle:withCallBackBlock:internalCallBackBlock:internalCallBackBlock没有被保留。

诀窍是将 is 存储在MyAlertView. 因此,在MyAlertView.m中添加以下内容:

@interface MyAlertView()
    @property(strong) UIAlertView *alertView;
@end

@implementation MyAlertView

@synthesize alertView;

...

并使用它来存储UIAlertView您创建的内容showWithTitle:withCallBackBlock:internalCallBackBlock:internalCallBackBlock

dispatch_async(dispatch_get_main_queue(), ^{
    self.alertView = [[UIAlertView alloc] initWithTitle:title message:title delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK" , nil];
    [self.alertView show];
});

PS 这真的很迂腐,但MyAlertView实际上并不是一个视图,所以你可能想要重命名它。

于 2012-06-05T23:11:46.647 回答