OS X Mavericks实现了一个新的API,以更方便地显示NSAlert :
- (void)beginSheetModalForWindow:(NSWindow *)sheetWindow completionHandler:(void (^)(NSModalResponse returnCode))handler是否有一种简单的方法可以在OS X 10.8及更早版本中支持的类别中创建类似的方法?
OS X Mavericks implemented a new API for more convenient displaying of NSAlert:
- (void)beginSheetModalForWindow:(NSWindow *)sheetWindow completionHandler:(void (^)(NSModalResponse returnCode))handlerIs there an easy way to create a similar method in a category that does the same thing but supported on OS X 10.8 and earlier?
最满意答案
是的,您可以使用基于委托的API来模拟类似的API。 唯一棘手的部分是让所有演员合适,因此它适用于ARC。 以下是NSAlert的一个类别,它提供了一个向后兼容的基于块的API:
NSAlert + BlockMethods.h
#import <Cocoa/Cocoa.h> @interface NSAlert (BlockMethods) -(void)compatibleBeginSheetModalForWindow: (NSWindow *)sheetWindow completionHandler: (void (^)(NSInteger returnCode))handler; @endNSAlert + 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回购 。
Yes, you can simulate a similar API using the delegate based API. The only tricky part is getting all the casts right so it works with ARC. Here's a category on NSAlert that provides a backward compatible block-based API:
NSAlert+BlockMethods.h
#import <Cocoa/Cocoa.h> @interface NSAlert (BlockMethods) -(void)compatibleBeginSheetModalForWindow: (NSWindow *)sheetWindow completionHandler: (void (^)(NSInteger returnCode))handler; @endNSAlert+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); } @endFor more info, see my NSAlertBlockMethods Github repo.
更多推荐
发布评论