- Block
- Block封裝了一段代碼,可以在任何時候執行
- Block可以作為函數參數或者函數的返回值,而其本身又可以帶輸入參數或返回值。
- 蘋果官方建議盡量多用block。在多線程、異步任務、集合遍歷、集合排序、動畫轉場用的很多
#include<stdio.h> int sum(int a,int b) { return a + b; } int main() { NSLog(@"%d",sum(5,6)); //如何定義block //void (^myblock) () = ^() { }; //類型(^block的名稱)(參數類型) = (參數類型) {代碼內容}; //使用:類似於函數調用
int (^Sumblock)(int,int) = ^(int a,int b){ return a + b; }; NSLog(@"%d",Sumblock(11,22)); void (^block) () = ^() // 若無參數,后面的()可以省略 { NSLog(@"------"); }; block(); //跟指針指向函數類似,能用block代替就用 int (*p)(int,int) = sum; int p1 = p(11,22); NSLog(@"%d",p1); return 0; }
- 在聲明的同時定義變量,然后賦值
int (^MySum)(int,int) = ^(int a,int b) {
return a + b;
};
- 也可先用typedef先聲明類型,再定義變量進行賦值
typedef int (^MySum)(int,int);
MySum sum = ^(int a,int b) {
return a + b;
};
// // ViewController.m // SlowWorker // // Created by Jierism on 16/7/31. // Copyright © 2016年 Jierism. All rights reserved. // #import "ViewController.h" @interface ViewController () @property (weak, nonatomic) IBOutlet UIButton *startButton; @property (weak, nonatomic) IBOutlet UITextView *resultsTextView; @property (weak, nonatomic) IBOutlet UIActivityIndicatorView *spinner; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (NSString *) fetchSomethingFromServer { [NSThread sleepForTimeInterval:1]; return @"Hi there"; } - (NSString *)processData:(NSString *)data { [NSThread sleepForTimeInterval:2]; return [data uppercaseString]; } - (NSString *)calculateFirstResult:(NSString *)data { [NSThread sleepForTimeInterval:3]; return [NSString stringWithFormat:@"Number of chars:%lu",(unsigned long)[data length]]; } - (NSString *)calculateSecondResult:(NSString *)data { [NSThread sleepForTimeInterval:4]; return [data stringByReplacingOccurrencesOfString:@"E" withString:@"e"]; } - (IBAction)doWork:(id)sender { self.resultsTextView.text = @""; NSDate *startTime = [NSDate date]; // 點擊后按鈕變為禁用狀態 self.startButton.enabled = NO; // 讓旋轉器轉動 [self.spinner startAnimating]; // 使用dispatch_get_global_queue(1.指定優先級,2.目前沒使用為0)函數,來抓取一個已經存在並始終可用的全局隊列 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(queue, ^{ NSString *fetchedData = [self fetchSomethingFromServer]; NSString *processedData = [self processData:fetchedData]; // 使用分派組(dispatch group),通過dispatch_group_async()函數異步分派的所有代碼塊設置為松散,以便盡可能快執行。如果可能,將他們分發給多個線程同時執行(並發). __block NSString *firstResult; __block NSString *secondResult; dispatch_group_t group = dispatch_group_create(); dispatch_group_async(group, queue, ^{ firstResult = [self calculateFirstResult:processedData]; }); dispatch_group_async(group, queue, ^{ secondResult = [self calculateSecondResult:processedData]; }); // 使用dispatch_group_notify()指定一個額外的代碼塊,讓它在組中的所有代碼塊運行完成時再執行。 dispatch_group_notify(group, queue, ^{ NSString *resultsSummary = [NSString stringWithFormat:@"First:[%@]\nSecond:[%@]",firstResult,secondResult]; // 調用分派函數,將工作傳回主線程 dispatch_async(dispatch_get_main_queue(), ^{ self.resultsTextView.text = resultsSummary; self.startButton.enabled = YES; [self.spinner stopAnimating]; }); NSDate *endTime = [NSDate date]; NSLog(@"Completed in %f seconds",[endTime timeIntervalSinceDate:startTime]);// 運行時間減少了 }); }); } @end