精通IOS開發-block使用與多線程

來源:互聯網
上載者:User

標籤:

  • 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

 

精通IOS開發-block使用與多線程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.