格式说明:void (^now)( void ) 格式: 返回值(^名称)参数
先主要发一些代码,等有时间再具体说明
代码一 : 主要是循环返回 i与3的积,并打印
.h文件
@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 => 3 iteration 2 => 6 iteration 3 => 9 iteration 4 => 12 iteration 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
本文介绍了iOS编程中Block的三种实用场景:循环迭代运算、类型定义简化及电影播放后的自动队列管理。通过具体代码实例展示了如何利用Block提高代码效率和可读性。
61

被折叠的 条评论
为什么被折叠?



