跨文件傳值
- 較常用的Block用法
- 過(guò)程:由
ViewController
調(diào)用BSGBlockMethod
的方法踊东,并于BSGBlockMethod.h
賦值并傳遞給ViewController
- 先設(shè)置
BSGBlockMethod
,后于ViewController
調(diào)用 - 也可以用做成屬性的形式進(jìn)行傳值
- 第一個(gè)是直接定義Block刚操,Block可以重復(fù)使用闸翅;第二種方法則是將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 <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直接嵌入方法中
- 名稱就不要在意了菊霜,封裝網(wǎng)絡(luò)請(qǐng)求的時(shí)候順便測(cè)試的
- 未封裝成單例坚冀,反正也沒(méi)什么大影響,用
[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 <Foundation/Foundation.h>
@interface BSGHTTPManager : NSObject
+(instancetype)manager;
//一個(gè)無(wú)關(guān)測(cè)試
-(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];
}
//測(cè)試
-(void)BSGBlockWithFirstString:(NSString *)aString secondString:(NSString *)bString backBlock:(void (^)(NSString *))blockMessage
{
NSString * resultStr = [aString stringByAppendingString:bString];
blockMessage(resultStr);
}
文件內(nèi)傳值
懶得寫
參考文章不一定看了
參考鏈接:iOS中Block的基礎(chǔ)用法
參考鏈接:一篇文章看懂iOS代碼塊Block