不明觉厉iOSUIiOS学习

iOS-block三种应用场景

2016-01-10  本文已影响3859人  船长_
1.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);
}
上一篇下一篇

猜你喜欢

热点阅读