我正在阅读推动极限的 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) 为什么要为dismiss 和cancel 块声明静态变量?这基本上是作为这个类别的 ivar 吗?
谢谢!