chevron-up bell reply instagram twitter2 feed3 finder search-25px-p0

Block in Objective-C

2017-04-08

A typical example of using block:

// Traditional block in method parameters
- (double)driveForDuration:( double)duration
          withVariableSpeed:(double (^)(double time) )speedFunction //block is in the normal function definition
                      steps:(int)numSteps {
     double odometer = 0.0;
     double dt = duration / numSteps;
     for (int i = 1; i <= numSteps; i++) {
          odometer += speedFunction(i *dt) * dt;
     }
     return odometer;
}


// main.m
#import <Foundation/Foundation.h>
#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, block as a varying variable
        [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;
}

Some fundamental features of Block:

  • speedFunction is actually a (anonymous) function name here, which it takes double time as the parameter, and return a double result;
  • speedFunction was only declared BUT not defined;
  • speedFunction is defined sperately/flexiably in the implementation.
  • Block is mainly for Asychronisation
  • Block is implemented as closures

Some typical scenarios that you can use Block

1. Block as a method parameter

This is quite often used in real world.

- (void)aMethodWithBlock:(returnType (^)(parameters))blockName {
        // your code
}

returnType: is the return value type that the block returns
parameters: paramters used in the block

// Example
-(void) saveWithCompletionBlock: (void (^)(NSArray *elements, NSError *error))completionBlock{
        // your code
}

// Ignore the return type, as it is void here
-(void) saveWithCompletionBlock: ^(NSArray *elements, NSError *error)completionBlock{
        // your code
}

// Ignore the paramter names
-(void) saveWithCompletionBlock: ^(NSArray*, NSError*)completionBlock{
        // your code
}

2. Block as a property

@property (nonatomic, copy) returnType (^blockName)(parameters);
// Example
@property (nonatomic,copy) void (^completionBlock)(NSArray *array, NSError *error);

// Ignore the return type: THIS IS WRONG! ⏬
@property (nonatomic,copy) ^completionBlock (NSArray *array, NSError *error);

// Ignore parameter names:
@property (nonatomic,copy) void (^completionBlock)(NSArray*, NSError *);


typedef a block

typedef     return type     (^ Block name)(block parameters);
typedef     double          (^SpeedFunction)(double );

An example on this:

// Traditional block in method parameters
- (double)driveForDuration:( double)duration
          withVariableSpeed:(double (^)(double time) )speedFunction //block 函数声明
                      steps:(int)numSteps {
     double odometer= 0.0;
     double dt = duration / numSteps;
     for (int i= 1; i <=numSteps; i ++) {
          odometer += speedFunction(i *dt) * dt;
     }
     return odometer;
}

// typedef block in method parameters
- (double)driveForDuration:( double)duration
          withVariableSpeed:(SpeedFunction )speedFunction //block 函数声明
                      steps:(int)numSteps {
     double odometer= 0.0;
     double dt = duration / numSteps;
     for (int i= 1; i <=numSteps; i ++) {
          odometer += speedFunction(i *dt) * dt;
     }
     return odometer;
}

Notice:

typedef a block vs. typedef a function

typedef void (^myBlock) (int a);

Defines a block named myBlcok. That is because myBlcok variable hold references to block. Similarly, you can have

typedef void (*myBlock) (int a);

Defines a function pointer.


Some good resources while using block:

http://fuckingblocksyntax.com
http://fuckingswiftblocksyntax.com

Reference
http://rypress.com/tutorials/objective-c/blocks
https://developer.apple.com/

arkilis

Make Your Comments