iOS开发 Block声明方式

1.写在方法里作为局部变量

returnType (^blockName)(parameterTypes) = ^returnType(parameters) {...};
  • returnType是返回值
  • blockName是block名称
  • parameterTypes是参数
    示例代码:
- (IBAction)test1:(id)sender {
    
    void (^testBlock)(NSString *) = ^void(NSString *name) {
        //self.nameLabel.text = name;
        NSLog(@"name:%@",name);
    };
    
    testBlock(@"1");
}

2.作为类的属性

@property (nonatomic, copy) returnType (^blockName)(parameterTypes)
  • returnType是返回值
  • blockName是block名称
  • parameterTypes是参数
    示例代码:
#import "DetailViewController.h"

@interface DetailViewController ()
@property (nonatomic, copy) void (^block)(NSInteger);
@end

@implementation DetailViewController

- (IBAction)test2:(id)sender {
    NSInteger index = 1;
    if (self.block) {
        self.block(index);
    }
}

3.作为方法参数

- (void)someMethodThatTakesABlock:(returnType (^)(parameterTypes))blockName;
  • returnType是返回值
  • blockName是block名称
  • parameterTypes是参数

示例代码:

- (void)methodTakesBlock:(void (^)(NSString *))blockName {
    
}

4.调用方法是传入的参数

[self someMethodThatTakesABlock:^returnType (parameters) {...}];
  • returnType是返回值
  • blockName是block名称
  • parameterTypes是参数

示例代码:

-(IBAction)test2:(id)sender {
    [self methodTakesBlock:^(NSString *name) {
        NSLog(@"name:%@",name);
    }];
}

5.自定义Block类型

typedef returnType (^TypeName)(parameterTypes);
TypeName blockName = ^returnType(parameters) {...};
  • returnType是返回值
  • blockName是block名称
  • parameterTypes是参数

示例代码:

typedef void (^MyBlock)(NSString *);

- (void)test5 {
    MyBlock myBlock = ^void(NSString *name) {
  
    };
    
    myBlock(@"123");
}

参考链接:iOS开发 Block声明方式

你可能感兴趣的:(iOS开发 Block声明方式)