我正在阅读突破极限的iOS 5,作者有一个基于块的警报视图的示例。 代码如下:
.h
typedef void (^DismissBlock)(int buttonIndex);
typedef void (^CancelBlock)();
+ (UIAlertView *)showAlertViewWithTitle:(NSString *)title
message:(NSString *)message
cancelButtonTitle:(NSString *)cancelButtonTitle
otherButtonTitles:(NSArray *)otherButtons
onDismiss:(DismissBlock)dismissed
onCancel:(CancelBlock)cancelled;
.m
static DismissBlock _dismissBlock;
static CancelBlock _cancelBlock;
+ (UIAlertView *)showAlertViewWithTitle:(NSString *)title
message:(NSString *)message
cancelButtonTitle:(NSString *)cancelButtonTitle
otherButtonTitles:(NSArray *)otherButtons
onDismiss:(DismissBlock)dismissed
onCancel:(CancelBlock)cancelled {
[_cancelBlock release];
_cancelBlock = [cancelled copy];
[_dismissBlock release];
_dismissBlock = [dismissed copy];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:[self self] cancelButtonTitle:cancelButtonTitle otherButtonTitles: nil];
for (NSString *buttonTitle in otherButtons) {
[alert addButtonWithTitle:buttonTitle];
}
[alert show];
return [alert autorelease];
}
+ (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
if (buttonIndex == [alertView cancelButtonIndex]) {
_cancelBlock();
}
else {
_dismissBlock(buttonIndex - 1); // cancel button is index 0
}
[_cancelBlock autorelease];
[_dismissBlock autorelease];
}
我对此实现有几个问题。
1) 如果我使用的是 ARC,在 showAlertViewWithTitle 方法中,我需要在复制块之前释放它吗? 为什么或为什么不呢?
2) 在 showAlertViewWithTitle: 方法中,他分配委托:[self self]。 这实际上是如何工作的? 我以前没有见过这个符号。
3) 为什么为关闭和取消块声明了静态变量? 这基本上是作为此类别的 ivar 吗?
谢谢!
1)使用ARC时,您无法调用任何发布或自动发布,因此不需要,您不需要调用释放。ARC 将在您分配副本时为您处理。
2)我也从未见过。我只是用"自我"。
3)类别不能有ivar。在这里使用静态是危险的,并且只有在您 100% 肯定您永远不会调用此 showAlertViewWithTitle:... 类方法时,当前显示警报视图时才有效。
就个人而言,由于需要静态,我不会将其作为UIAlertView的类别方法。我会创建一个常规类(MyAlertView或类似类)来扩展UIAlertView并添加一个新的"show"方法,该方法采用两个块参数。然后,您的自定义类可以为块提供适当的 ivar。