iOS Block简单应用

跨文件传值

  • 较常用的Block用法
  • 过程:由ViewController调用BSGBlockMethod的方法,并于BSGBlockMethod.h赋值并传递给ViewController
  • 先设置BSGBlockMethod,后于ViewController调用
  • 也可以用做成属性的形式进行传值
  • 第一个是直接定义Block,Block可以重复使用;第二种方法则是将Block直接嵌入方法中,不需要专门在方法外定义Block
定义Block的方法

ViewController.m:

#import "BSGBlockMethod.h"


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    BSGBlockMethod * BlockMethod = [[BSGBlockMethod alloc]init];
    [BlockMethod BSGManagerWithBlock:^(NSString *a, NSString *b) {
        NSLog(@"a:%@,b:%@",a,b);
    }];
    
    
    
}

BSGBlockMethod.h:

#import 

@interface BSGBlockMethod : NSObject


typedef void(^MyBlock)(NSString* a,NSString * b);

-(void)BSGManagerWithBlock:(MyBlock)TheBlock;


@end

BSGBlockMethod.m:


#import "BSGBlockMethod.h"

@implementation BSGBlockMethod


-(void)BSGManagerWithBlock:(MyBlock)TheBlock
{
    NSString * a = @"hi~";
    NSString * b = @"~hello";
    
    
    TheBlock(a,b);
    
}


@end

将Block直接嵌入方法中
  • 名称就不要在意了,封装网络请求的时候顺便测试的
  • 未封装成单例,反正也没什么大影响,用[BSGHTTPManager manager]单纯是为了随大流

ViewController.m:

#import "BSGHTTPManager.h"

- (void)viewDidLoad {
    [super viewDidLoad];
    
    BSGHTTPManager * BSGManager = [BSGHTTPManager manager];
    
    [BSGManager BSGBlockWithFirstString:@"hello " secondString:@"xigua!" backBlock:^(NSString *resultString) {
        NSLog(@"result:%@",resultString);
    }];
    
}

BSGHTTPManager.h:


#import 

@interface BSGHTTPManager : NSObject

+(instancetype)manager;

//一个无关测试
-(void)BSGBlockWithFirstString:(NSString *)aString secondString:(NSString *)bString backBlock:(void(^)(NSString * resultString))blockMessage;

BSGHTTPManager.m:


#import "BSGHTTPManager.h"

#import 

@implementation BSGHTTPManager


+(instancetype)manager{
    
    return [[[self class] alloc] init];
    
}



//测试
-(void)BSGBlockWithFirstString:(NSString *)aString secondString:(NSString *)bString backBlock:(void (^)(NSString *))blockMessage
{
    
    NSString * resultStr = [aString stringByAppendingString:bString];
    
    blockMessage(resultStr);
    
    
}


文件内传值

懒得写

参考文章不一定看了

参考链接:iOS中Block的基础用法
参考链接:一篇文章看懂iOS代码块Block

你可能感兴趣的