Iphone 使用Blocks
?.m文件 ?调用时: ?也可以这样: ?结果: ?代码二: 使用TypeDef 简化代码,使代码更可读 .h文件 ?.m文件 ?代码三: 当播放时,自动删除已经播放的名称 .h文件 ?.m文件 ?引用代码 ? Notice that the block uses the local ? 参考链接:http://pragmaticstudio.com/blog/2010/9/15/ios4-blocks-2@interface Worker : NSObject {} + (void)iterateFromOneTo:(int)limit withBlock:(int (^)(int))block; @end
@implementation Worker + (void)iterateFromOneTo:(int)limit withBlock:(int (^)(int))block { for (int i = 1; i <= limit; i++) { int result = block(i); NSLog(@"iteration %d => %d", i, result); }} @end
[Worker iterateFromOneTo:5 withBlock:^(int number) { return number * 3;}];
int (^tripler)(int) = ^(int number) { return number * 3;}; [Worker iterateFromOneTo:5 withBlock:tripler];
iteration 1 => 3iteration 2 => 6iteration 3 => 9iteration 4 => 12iteration 5 => 15
typedef int (^ComputationBlock)(int); @interface Worker : NSObject {} + (void)iterateFromOneTo:(int)limit withBlock:(ComputationBlock)block; @end
@implementation Worker + (void)iterateFromOneTo:(int)limit withBlock:(ComputationBlock)block { for (int i = 1; i <= limit; i++) { int result = block(i); NSLog(@"iteration %d => %d", i, result); }} @end
typedef void (^MoviePlayerCallbackBlock)(NSString *); @interface MoviePlayer : NSObject {} @property (nonatomic, copy) MoviePlayerCallbackBlock callbackBlock; - (id)initWithCallback:(MoviePlayerCallbackBlock)block;- (void)playMovie:(NSString *)title; @end
#import "MoviePlayer.h" @implementation MoviePlayer @synthesize callbackBlock; - (id)initWithCallback:(MoviePlayerCallbackBlock)block { if (self = [super init]) { self.callbackBlock = block; } return self;} - (void)playMovie:(NSString *)title { // play the movie self.callbackBlock(title);} - (void)dealloc { [callbackBlock release]; [super dealloc];} @end
NSMutableArray *movieQueue = [NSMutableArray arrayWithObjects:@"Inception", @"The Book of Eli", @"Iron Man 2", nil]; MoviePlayer *player = [[MoviePlayer alloc] initWithCallback:^(NSString *title) { [movieQueue removeObject:title];}]; for (NSString *title in [NSArray arrayWithArray:movieQueue]) { [player playMovie:title];};
movieQueue
variable, which becomes part of the state of the block. When the block is called it removes the movie title from the movieQueue
array even though it’s out of scope by that time. After all the movies have been played, the movieQueue
will be empty.