iOS-block三种应用场景

  • 1.把block保存成对象中的属性,在恰当的时刻调用
iOS-block三种应用场景_第1张图片
1.png
  • 2.把block当成方法的参数使用,block的调用在是在方法内部,在外界写block的实现(最常用)

    iOS-block三种应用场景_第2张图片
    2.png
  • 3.把block当成方法的返回值(比较少用)

    iOS-block三种应用场景_第3张图片
    3.png

示例1

1.在Person类中

@interface Person : NSObject
@property (nonatomic,strong) void(^myBlock)(int,int);
@end

2.在ViewController类中

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    int a = 12;
    int b = 11;
    Person *p = [[Person alloc] init];
    p.myBlock(a,b);
}

示例2

1.在Person类中

@interface Person : NSObject
- (void)eat:(void(^)())block;
@end

@implementation Person
- (void)eat:(void (^)())block
{
    block();
}
@end

2.在ViewController类中

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    // 方式1.先定义,在赋值
    //    void(^block)() = ^() {
    //        NSLog(@"吃东西");
    //    };
    //
    //    [p eat:block];

    // 方式2.直接写block
    [p eat:^{
        NSLog(@"吃东西");
    }];
}

示例3

1.在Person类中

@interface Person : NSObject
- (void(^)(int))run;
@end

@implementation Person
- (void (^)(int))run
{
    return ^(int b){
        NSLog(@"跑了--%d米",b);
    };
}
@end

2.在ViewController类中

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
     p.run(5);
}

你可能感兴趣的:(Block)