前言
這篇隨記就是向大家簡(jiǎn)單介紹下block以及一些簡(jiǎn)單地用法.我相信對(duì)于一些初學(xué)者會(huì)有一些幫助的.
什么是block
Block(塊)在其他編程語(yǔ)言中也有相似的概念, 叫閉包
Block和函數(shù)指針?lè)浅O嗨?技巧:將(*p) 換成(^block))
Block本質(zhì)是匿名函數(shù)
聲明一個(gè)block變量.
block跟函數(shù)類(lèi)型是一樣的
分為:
1* 無(wú)參數(shù), 無(wú)返回值
2* 無(wú)參數(shù), 有返回值
3* 有參數(shù), 無(wú)返回值
4* 有參數(shù), 有返回值
例:
變量類(lèi)型: int (^)(int, int)
變量名: handler
int (^handler)(int, int) = NULL;
block的使用
用法跟函數(shù)也是一樣的
block的實(shí)現(xiàn)和調(diào)用.在適當(dāng)?shù)貢r(shí)機(jī)調(diào)用block,然后執(zhí)行實(shí)現(xiàn)中的方法(代碼).完成一系列的功能
下面我就為大家簡(jiǎn)單介紹一些block的使用:
界面之間的傳值
第一種:將block設(shè)置為屬性
重命名void(^)(NSString *)類(lèi)型 命名為Block 這樣方便書(shū)寫(xiě).
typedef void(^Block)(NSString *);
@interface TwoOfViewController : UIViewController
聲明一個(gè)Block屬性
@property (nonatomic, copy) void (^handleString)(NSString *);
// 下面這個(gè)就是用重命名的block定義的
@property (nonatomic, copy) Block handleStr;
@end
然后在 (button) 適當(dāng)時(shí)機(jī)調(diào)用block
- (IBAction)handleBlock:(id)sender {
// 調(diào)用Block
self.handleString(self.textfiled.text);
參數(shù) 位子就是你要傳得值
}
下面是在需要傳入的界面 實(shí)現(xiàn)block
TwoOfViewController *second = [segue destinationViewController];
//Block實(shí)現(xiàn)部分
//Block實(shí)現(xiàn)體中, 對(duì)對(duì)象進(jìn)行強(qiáng)引用, 避免循環(huán)引用, 修改為弱引用.
//ARC下. __weak 修飾詞
//MRC下. __block 修飾詞
__weak typeof(self) weakself = self;
實(shí)現(xiàn)部分
second.handleString = ^(NSString * str)
{
運(yùn)用帶入的參數(shù), 實(shí)現(xiàn)一些功能
weakself.label.text = str;
};
第二種: 將block作為方法的參數(shù)
跟屬性傳值是一樣的,只是將block作為方法的參數(shù).
然后在第二界面調(diào)用方法,實(shí)現(xiàn)block.完成一些功能.
但是要記住 : 調(diào)用方法并不是調(diào)用block.. 可以在方法中完成block的調(diào)用...
完成傳值...
Block實(shí)現(xiàn)網(wǎng)絡(luò)請(qǐng)求回調(diào)
#import "NetWord.h"
@implementation NetWord
下面是封裝的一個(gè)解析網(wǎng)絡(luò)數(shù)據(jù)的類(lèi)方法..方法中有block參數(shù)
+ (void)networkHandlerGetWithURL:(NSString *)urlString completionHandler:(void (^)(id result, NSURLResponse *response, NSError *error))block
{
//url中只支持ASCII嗎, 如果出現(xiàn)中文需要進(jìn)行轉(zhuǎn)碼
//url中的中文一般出現(xiàn)在查詢(xún)部分, 所以將查詢(xún)部分進(jìn)行轉(zhuǎn)碼.
NSString *newStr = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//Core API
NSURLSession *session = [NSURLSession sharedSession];
//URL
NSURL *url = [NSURL URLWithString:newStr];
//session添加任務(wù)
NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//數(shù)據(jù)解析
if (data) {
id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//進(jìn)入主線(xiàn)程, 將result等回調(diào)出去
dispatch_async(dispatch_get_main_queue(), ^{
// 通過(guò)block回調(diào)
block(result, response, error);
});
}
}];
[task resume];
}
下面是調(diào)用方法時(shí)候block的實(shí)現(xiàn)
- (void)handleData
{
[NetWord networkHandlerGetWithURL:@"http://api.m.mtime.cn/News/NewsList.api?pageIndex=1" completionHandler:^(id result, NSURLResponse *response, NSError *error) {
// 這里的實(shí)現(xiàn)只是簡(jiǎn)單打印下.還可以使用block參數(shù)做一些你想要得功能
NSLog(@"%@",result);
}];
}
Block實(shí)現(xiàn)自定義View點(diǎn)擊事件回調(diào)
@interface CustomeView ()
@property (strong, nonatomic) IBOutlet UIView *view;
//聲明Block屬性, 參數(shù)是button
@property (nonatomic, copy) void (^handleEdit)(UIButton *);
@property (nonatomic, copy) void (^handleDele)(UIButton *);
@end
@implementation CustomeView
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
[[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil];
self.view.frame = self.bounds;
[self addSubview:self.view];
}
return self;
}
#pragma mark - 點(diǎn)擊事件.
下面?zhèn)z個(gè)方法是button的點(diǎn)擊事件. 在點(diǎn)擊button的時(shí)候調(diào)用block,
- (IBAction)handleEdit:(id)sender {
// 調(diào)用Block
self.handleEdit((UIButton *)sender);
}
- (IBAction)handleDelete:(id)sender {
self.handleDele((UIButton *)sender);
}
下面這個(gè)方法是聲明出去的,目的是給屬性的倆個(gè)block賦值
- (void)clickEditBtn:(void (^)(UIButton *editBtn))handleEdit delebtn:(void (^)(UIButton *deleBtn))handlerDele
{
//Block屬性賦值
self.handleEdit = handleEdit;
self.handleDele = handlerDele;
}
下面是調(diào)用倆個(gè)block的賦值的方法
- (void)viewDidLoad {
[super viewDidLoad];
當(dāng)調(diào)用這個(gè)方法的時(shí)候. 先走了方法中的給屬性賦值代碼,這個(gè)時(shí)候?qū)傩缘闹羔樢呀?jīng)指向調(diào)用方法時(shí)候的block.
當(dāng)點(diǎn)擊按鈕button的時(shí)候.調(diào)用block.然后走下面方法中block 的實(shí)現(xiàn)部分
[self.customview clickEditBtn:^(UIButton *editBtn) {
NSLog(@"點(diǎn)擊了編輯");
[editBtn setTitle:@"wangdali" forState:UIControlStateNormal];
self.view.backgroundColor = [UIColor redColor];
UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(50, 400, 100, 50)];
[self.view addSubview:lable];
lable.text = editBtn.titleLabel.text;
} delebtn:^(UIButton *deleBtn)
NSLog(@"點(diǎn)擊了刪除");
}];
}
block實(shí)現(xiàn)自定義View點(diǎn)擊事件回調(diào)有什么作用那:
因?yàn)樽远x的view中的button 在正常情況下,只能做一些局限于自定義View界面的事情...
可是...當(dāng)用block時(shí)候..這個(gè)觸發(fā)消息會(huì)將button的屬性或者更多地屬性帶到其他界面.在其他界面完成關(guān)于其他界面的操作.
總結(jié)
block的基本用法其實(shí)并不是很難.只要理解了block是什么,實(shí)現(xiàn)原理就可以運(yùn)用了
記住倆個(gè)步驟:
1.需要找到適當(dāng)?shù)貢r(shí)機(jī)調(diào)用block,傳入你想在實(shí)現(xiàn)中用到的參數(shù).(block只有調(diào)用了才走實(shí)現(xiàn)部分,,,(注意:當(dāng)block作為方法參數(shù)時(shí)候,調(diào)用方法,并不是調(diào)用了block..block需要單獨(dú)調(diào)用)
- 在你需要用到block中得參數(shù).或者需要觸發(fā)某個(gè)事件的時(shí)候,實(shí)現(xiàn)block,在block的實(shí)現(xiàn)方法中完成你想要的功能
這就是我對(duì)block的簡(jiǎn)單介紹,希望對(duì)有需要的人有些幫助.
這也是自己的理解,一定會(huì)有不透徹或者問(wèn)題.希望大神可以提出寶貴意見(jiàn).謝謝