首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > Iphone >

Iphone 应用Blocks

2012-08-28 
Iphone 使用Blocks@interface Worker : NSObject {} + (void)iterateFromOneTo:(int)limit withBlock:(int

Iphone 使用Blocks

@interface Worker : NSObject {} + (void)iterateFromOneTo:(int)limit withBlock:(int (^)(int))block; @end

?.m文件

@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 简化代码,使代码更可读

.h文件

typedef int (^ComputationBlock)(int); @interface Worker : NSObject {} + (void)iterateFromOneTo:(int)limit withBlock:(ComputationBlock)block; @end

?.m文件

@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

?代码三: 当播放时,自动删除已经播放的名称

.h文件

typedef void (^MoviePlayerCallbackBlock)(NSString *); @interface MoviePlayer : NSObject {} @property (nonatomic, copy) MoviePlayerCallbackBlock callbackBlock; - (id)initWithCallback:(MoviePlayerCallbackBlock)block;- (void)playMovie:(NSString *)title; @end

?.m文件

#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];};

?

Notice that the block uses the local 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.

?

参考链接:http://pragmaticstudio.com/blog/2010/9/15/ios4-blocks-2