// Car.h #import @interfaceCar : NSObject @propertydouble odometer; - (void)driveForDuration:(double)duration withVariableSpeed:(double (^)(double time))speedFunction steps:(int)numSteps; @end //调用block // Car.m #import "Car.h" @implementationCar @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, constchar * 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) { return5.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); } return0; }
定义Block类型
1 2 3 4 5 6 7 8 9 10
// Car.h #import // Define a new type for the block typedefdouble (^SpeedFunction)(double); @interfaceCar : NSObject @property double odometer; - (void)driveForDuration:(double)duration withVariableSpeed:(SpeedFunction)speedFunction steps:(int)numSteps; @end