Block是ios 4的新东西,有了它,源码的逻辑将更清楚,代码的可读性将提高。熟悉函数指针的朋友对Block不会感冒的,因为它们实质是一样的,只是叫清一不样。今天将实战BLOCK,我们将封装一个支持Block的UIActionSheet。好了废话少说,直接上代码:
PLActionSheet.h
#import <UIKit/UIKit.h> /** * A simple block-enabled API wrapper on top of UIActionSheet. */ @interface PLActionSheet : NSObject <UIActionSheetDelegate> { @private UIActionSheet *_sheet; NSMutableArray *_blocks; } - (id) initWithTitle: (NSString *) title; - (void) setCancelButtonWithTitle: (NSString *) title block: (void (^)()) block; - (void) addButtonWithTitle: (NSString *) title block: (void (^)()) block; - (void) showInView: (UIView *) view; @end
PLActionSheet.m
#import "PLActionSheet.h" @implementation PLActionSheet - (id) initWithTitle: (NSString *) title { if ((self = [super init]) == nil) return nil; /* Initialize the sheet */ _sheet = [[UIActionSheet alloc] initWithTitle: title delegate: self cancelButtonTitle: nil destructiveButtonTitle: nil otherButtonTitles: nil]; /* Initialize button -> block array */ _blocks = [[NSMutableArray alloc] init]; return self; } - (void) dealloc { _sheet.delegate = nil; [_sheet release]; [_blocks release]; [super dealloc]; } - (void) setCancelButtonWithTitle: (NSString *) title block: (void (^)()) block { [self addButtonWithTitle: title block: block]; _sheet.cancelButtonIndex = _sheet.numberOfButtons - 1; } - (void) addButtonWithTitle: (NSString *) title block: (void (^)()) block { [_blocks addObject: [[block copy] autorelease]]; [_sheet addButtonWithTitle: title]; } - (void) showInView: (UIView *) view { [_sheet showInView: view]; /* Ensure that the delegate (that's us) survives until the sheet is dismissed */ [self retain]; } - (void) actionSheet: (UIActionSheet *) actionSheet clickedButtonAtIndex: (NSInteger) buttonIndex { /* Run the button's block */ if (buttonIndex >= 0 && buttonIndex < [_blocks count]) { void (^b)() = [_blocks objectAtIndex: buttonIndex]; b(); } /* Sheet to be dismissed, drop our self reference */ [self release]; } @end
用法如下:
- (void) displaySheet { PLActionSheet *sheet = [[PLActionSheet alloc] initWithTitle: @"Destination"]; /* A re-usable block that simply displays an alert message */ void (^alert)(NSString *) = ^(NSString *message) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Destination Selected" message: message delegate: nil cancelButtonTitle: @"OK" otherButtonTitles: nil]; [alert show]; [alert release]; }; [sheet addButtonWithTitle: @"Work" block: ^{ alert(@"Work selected"); }]; [sheet addButtonWithTitle: @"Home" block: ^{ alert(@"Home selected"); }]; [sheet addButtonWithTitle: @"School" block: ^{ alert(@"School selected"); }]; [sheet setCancelButtonWithTitle: @"Cancel" block: ^{}]; [sheet showInView: self.window]; [sheet release]; }
采用BLOCK的方法,源码可读性大大增强。如果我们在同一个Controller里需要多个UIActionSheet, 而只有一个delegate方法,那在这个delegate方法里就要跟踪现在是哪一个UIActionSheet,这样就会有很多if else的代,也难于维护。以后将多采用BLOCK来写程序了。