首页 > 代码库 > IOS_Block_使用

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 = http://www.mamicode.com/%d", [c calcNum1:10 withNum2:30 andCalcWith:^int(int x, int y) {>
//
//  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



IOS_Block_使用