block的创建,不带参数的block,block闭包,修改非局部变量,block作为函数参数,定义block类型,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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、Objective-C发展史 Objective-C从1983年诞生,已经走过了30多年的历程。随着时间的推移...
    没事蹦蹦阅读 5,903评论 12 34
  • 《Objective-C高级编程》这本书就讲了三个东西:自动引用计数、block、GCD,偏向于从原理上对这些内容...
    WeiHing阅读 9,902评论 10 69
  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,211评论 30 472
  • 前言 Blocks是C语言的扩充功能,而Apple 在OS X Snow Leopard 和 iOS 4中引入了这...
    小人不才阅读 3,786评论 0 23
  • 在介绍Block之前通过一个简单的应用场景认识下Block 场景描述如下:TableView上面有多个Custom...
    黑_白_灰阅读 1,416评论 4 29