IOS_Block_使用

int main(int argc, const char * argv[]) {
    @autoreleasepool {

        //first
        void (^myBlock)() = ^{
            NSLog(@"myBlock execute");
        };
        myBlock();

        //second return value
        int (^sum)(int, int) = ^int(int x, int y){
            return x+y;
        };
        NSLog(@"sum = %d", sum(2, 6));

        //third
        Calc *c = [[Calc alloc] init];
        NSLog(@"s = %d", [c calcNum1:10 withNum2:20 andCalcWith:sum]);

        NSLog(@"value = %d", [c calcNum1:10 withNum2:30 andCalcWith:^int(int x, int y) {
            return x*y;
        }]);

    }
    return 0;
}
//
//  Calc.h
//

#import <Foundation/Foundation.h>

typedef int (^calcBlock)(int, int);

@interface Calc : NSObject

-(int) calcNum1:(int)num1 withNum2:(int)num2 andCalcWith:(calcBlock)calc;

@end
//
//  Calc.m
//

#import "Calc.h"

@implementation Calc

- (int)calcNum1:(int)num1 withNum2:(int)num2 andCalcWith:(calcBlock)calc
{
    return calc(num1, num2);
}

@end
时间: 2024-10-30 00:35:38

IOS_Block_使用的相关文章