Block

简介

block可以当做匿名函数,可以在两个对象间将语句当做数据来进行传递。具有封闭性closure,方便取得上下文相关状态信息。

Block的创建

  • 可以如声明函数那样声明一个block变量
  • 定义函数的方法定义block
  • 把block当做一个函数来调用
int main(int argc, const char * argv[]) {
     @autoreleasepool {
     // Declare the block variable
     double (^distanceFromRateAndTime)(double rate, double time);

     // Create and assign the block
     distanceFromRateAndTime = ^double(double rate, double time) {
          return rate * time;
     };
     // Call the block
     double dx = distanceFromRateAndTime(35, 1.5);

     NSLog(@"A car driving 35 mph will travel "
          @"%.2f miles in 1.5 hours.", dx);
     }
     return 0;
}

不带参数的Block

block可以简写为^ { … }

double (^randomPercent)(void) = ^ {
     return (double)arc4random() / 4294967295;
};
NSLog(@"Gas tank is %.1f%% full”, randomPercent() * 100);

Block的闭包(closure)

block内部可以访问定义在block外部的非局部变量。非局部变量会以拷贝形式存储到block中。

NSString *make = @"Honda";
NSString *(^getFullCarName)(NSString *) = ^(NSString *model) {
     return [make stringByAppendingFormat:@" %@", model];
};
NSLog(@"%@", getFullCarName(@"Accord")); // Honda Accord

// Try changing the non-local variable (it won't change the block)
make = @"Porsche";
NSLog(@"%@", getFullCarName(@"911 Turbo")); // Honda 911 Turbo

修改非局部变量

用__block存储修饰符号(storage modifier)声明非局部变量

__block int i = 0;
int (^count)(void) = ^ {
     i += 1;
     return i;
};
NSLog(@"%d", count()); // 1
NSLog(@"%d", count()); // 2
NSLog(@"%d", count()); // 3

Block作为函数的参数

// Car.h
#import

@interface Car : NSObject

@property double odometer;

- (void)driveForDuration:(double)duration
     withVariableSpeed:(double (^)(double time))speedFunction
     steps:(int)numSteps;

@end

//调用block
// Car.m
#import "Car.h"

@implementation Car

@synthesize odometer = _odometer;

- (void)driveForDuration:(double)duration
     withVariableSpeed:(double (^)(double time))speedFunction
     steps:(int)numSteps {
     double dt = duration / numSteps;
     for (int i=1; i<=numSteps; i++) {
          _odometer += speedFunction(i*dt) * dt;
     }
}

@end

//在main函数中block定义在另一个函数的调用过程中。
// main.m
#import
#import "Car.h"

int main(int argc, const char * argv[]) {
     @autoreleasepool {
          Car *theCar = [[Car alloc] init];

          // Drive for awhile with constant speed of 5.0 m/s
          [theCar driveForDuration:10.0
               withVariableSpeed:^(double time) {
               return 5.0;
               } steps:100];
          NSLog(@"The car has now driven %.2f meters", theCar.odometer);

          // Start accelerating at a rate of 1.0 m/s^2
          [theCar driveForDuration:10.0
               withVariableSpeed:^(double time) {
               return time + 5.0;
               } steps:100];
          NSLog(@"The car has now driven %.2f meters", theCar.odometer);
     }
     return 0;
}

定义Block类型

// Car.h
#import

// Define a new type for the block
typedef double (^SpeedFunction)(double);

@interface Car : NSObject

@property double odometer;

- (void)driveForDuration:(double)duration
     withVariableSpeed:(SpeedFunction)speedFunction
     steps:(int)numSteps;

@end

风险

block会存在导致retain cycles的风险,如果发送者需要 retain block 但又不能确保引用在什么时候被赋值为 nil, 那么所有在 block 内对 self 的引用就会发生潜在的 retain 环。NSOperation 是使用 block 的一个好范例。因为它在一定的地方打破了 retain 环,解决了上述的问题。

self.queue = [[NSOperationQueue alloc] init];
MyOperation *operation = [[MyOperation alloc] init];
operation.completionBlock = ^{
     [self finishedOperation];
};
[self.queue addOperation:operation];

另一个解决方法

@interface Encoder ()
@property (nonatomic, copy) void (^completionHandler)();
@end

@implementation Encoder

- (void)encodeWithCompletionHandler:(void (^)())handler
{
     self.completionHandler = handler;
     // 进行异步处理...
}

// 这个方法会在完成后被调用一次
- (void)finishedEncoding
{
     self.completionHandler();
     self.completionHandler = nil; //一旦任务完成就设置为nil
}

@end

作者

作者

江湖

发布于

2016-06-18

更新于

2016-06-18

许可协议

CC BY-NC 4.0

评论

Your browser is out-of-date!

Update your browser to view this website correctly.  Update my browser now

×