iOSiOS基础小知识

iOS Block简单应用

2017-09-13  本文已影响1人  清都

跨文件传值

定义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 <Foundation/Foundation.h>

@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直接嵌入方法中

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 <Foundation/Foundation.h>

@interface BSGHTTPManager : NSObject

+(instancetype)manager;

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

BSGHTTPManager.m:


#import "BSGHTTPManager.h"

#import <AFHTTPSessionManager.h>

@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

上一篇下一篇

猜你喜欢

热点阅读