是的,您可以使用基於委託的API來模擬類似的API。唯一棘手的部分是讓所有演員合適,因此它適用於ARC。下面是提供了一個向後兼容的基於塊的API上NSAlert
類別:
NSAlert + BlockMethods.h
#import <Cocoa/Cocoa.h>
@interface NSAlert (BlockMethods)
-(void)compatibleBeginSheetModalForWindow: (NSWindow *)sheetWindow
completionHandler: (void (^)(NSInteger returnCode))handler;
@end
NSAlert + BlockMethods.m
#import "NSAlert+BlockMethods.h"
@implementation NSAlert (BlockMethods)
-(void)compatibleBeginSheetModalForWindow: (NSWindow *)sheetWindow
completionHandler: (void (^)(NSInteger returnCode))handler
{
[self beginSheetModalForWindow: sheetWindow
modalDelegate: self
didEndSelector: @selector(blockBasedAlertDidEnd:returnCode:contextInfo:)
contextInfo: (__bridge_retained void*)[handler copy] ];
}
-(void)blockBasedAlertDidEnd: (NSAlert *)alert
returnCode: (NSInteger)returnCode
contextInfo: (void *)contextInfo
{
void(^handler)(NSInteger) = (__bridge_transfer void(^)(NSInteger)) contextInfo;
if (handler) handler(returnCode);
}
@end
欲瞭解更多信息,請參閱我的NSAlertBlockMethods Github repo。