iOS开发-block使用与多线程
- Block
- Block封装了一段代码,可以在任何时候执行
- Block可以作为函数参数或者函数的返回值,而其本身又可以带输入参数或返回值。
- 苹果官方建议尽量多用block。在多线程、异步任务、集合遍历、集合排序、动画转场用的很多
#include<stdio.h>
int sum(int a,int b)
{
return a + b;
} int main()
{ NSLog(@"%d",sum(,)); //如何定义block
//void (^myblock) () = ^() { };
//类型(^block的名称)(参数类型) = (参数类型) {代码内容};
//使用:类似于函数调用
int (^Sumblock)(int,int) = ^(int a,int b){
return a + b;
};
NSLog(@"%d",Sumblock(,));
void (^block) () = ^() // 若无参数,后面的()可以省略
{
NSLog(@"------");
};
block();
//跟指针指向函数类似,能用block代替就用
int (*p)(int,int) = sum;
int p1 = p(,);
NSLog(@"%d",p1);
return ;
}
- 在声明的同时定义变量,然后赋值
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:];
return @"Hi there";
} - (NSString *)processData:(NSString *)data
{
[NSThread sleepForTimeInterval:];
return [data uppercaseString];
} - (NSString *)calculateFirstResult:(NSString *)data
{
[NSThread sleepForTimeInterval:];
return [NSString stringWithFormat:@"Number of chars:%lu",(unsigned long)[data length]];
} - (NSString *)calculateSecondResult:(NSString *)data
{
[NSThread sleepForTimeInterval:];
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, );
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使用与多线程的更多相关文章
- iOS开发--Block
iOS开发--Block 1.什么是Block,block 的作用 ui开发和网络常见功能实现回调,按钮的事件处理方法是回调方法以及网络下载后的回调处理 (1)按钮 target-action 一 ...
- iOS开发——Block详解
iOS开发--Block详解 1. Block是什么 代码块 匿名函数 闭包--能够读取其他函数内部变量的函数 函数变量 实现基于指针和函数指针 实现回调的机制 Block是一个非常有特色的语法,它可 ...
- ios开发 block语句块
ios开发 block语句块 1.block 理解为匿名函数 2.block变量的定义 //定义block变量,^表示定义block //技巧:函数名左右加括号,在函数名前面在加^ void (^bl ...
- iOS开发之再探多线程编程:Grand Central Dispatch详解
Swift3.0相关代码已在github上更新.之前关于iOS开发多线程的内容发布过一篇博客,其中介绍了NSThread.操作队列以及GCD,介绍的不够深入.今天就以GCD为主题来全面的总结一下GCD ...
- iOS开发中GCD在多线程方面的理解
GCD为Grand Central Dispatch的缩写. Grand Central Dispatch (GCD)是Apple开发的一个多核编程的较新的解决方法.在Mac OS X 10.6雪豹中 ...
- iOS开发Block的使用
Block 是从 iOS4引入的,在日常开发中,会经常用到Block.特别是在多线程中,Block的用处更广泛.而且,Block不仅可以接收参数,其本身也可以作为参数,因此,Block的功能非常强大. ...
- iOS开发-Block回调
关于Block之前有一篇文章已经写过一篇文章Object-C-代码块Block回顾,不过写的比较浅显,不能体现出Block在实际开发中的重要性,关于Block的基础知识,可以参考之前的博客.在实际开发 ...
- iOS开发 -------- Block技术中的weak - strong
一 Block是什么? 我们使用^运算符来声明一个Block变量,而且在声明完一个Block变量后要像声明普通变量一样,后面要加; 声明Block变量 int (^block)(int) = NULL ...
- IOS开发 Block的学习
苹果公司正在大力推广Block块语法的使用,据说Block会迟早取代一般协议代理的使用. Block最大的作用是函数回调,简化代码. 在ios中,将blocks当成对象来处理,它封装了一段代码,这段代 ...
随机推荐
- aspx中的表单验证 jquery.validate.js 的使用 以及 jquery.validate相关扩展验证(Jquery表单提交验证插件)
这一期我们先讲在aspx中使用 jquery.validate插件进行表单的验证, 关于MVC中使用 validate我们在下一期中再讲 上面是效果,下面来说使用步骤 jQuery.Valid ...
- LeetCode Find Minimum in Rotated Sorted Array 旋转序列找最小值(二分查找)
题意:有一个有序序列A,其内部可能有部分被旋转了,比如A[1...n]被转成A[mid...n]+A[1...mid-1],如果被旋转,只有这种形式.问最小元素是?(假设没有重复元素) 思路:如果是序 ...
- django - get_or_create() 使用提醒
[omron - debug] user_id建表的时候,不能使用unique,因为一个用户,可能有多个product_id,相对应的是,get_or_create()中的查询参数,如果在建表中有un ...
- FU-A分包方式,以及从RTP包里面得到H.264数据和AAC数据的方法。。
[原创] RFC3984是H.264的baseline码流在RTP方式下传输的规范,这里只讨论FU-A分包方式,以及从RTP包里面得到H.264数据和AAC数据的方法. 1.单个NAL包单元 12字节 ...
- cocoapods 终极方案
最近各种错误, 全部刷新 再说 sudo gem install -n /usr/local/bin cocoapods $ sudo gem update --system // 先更新gem $ ...
- MVC&WebForm对照学习:传值方式
刚从webform开发转到mvc,如果说像路由这样稍微复杂一点的知识点还可以暂时先放一放(前提是默认的路由规则基本满足大部分需求),那有个问题在快速开发中,我想是必须要当即解决的,那就是webform ...
- COCOS2D-X学习笔记(一)-----Node类的学习
Node类(在3.0版本以下叫CCNode):节点类. 本文记录以下几个方法的学习笔记: init()和onEnter()这俩个方法都是CCNode的方法.其区别如下: 1.其被调用的顺序是先init ...
- delphi中计算指定日期是该月第几周的函数
NthDayOfWeek 计算并返回指定日期是该月第几周 Unit:DateUtils function NthDayOfWeek(const AValue: TDateTime): Word; ...
- win7和centos双系统安装
几年之前为了安装xp和linux的双系统曾折腾了好多天,今天为了安装这个win7和centos双系统,也折腾了两天多,哦,我的天,安装个双系统,怎么这么麻烦呢? 没有来得及整理,先铺上草稿,供同志们参 ...
- link 参数
-all-static do not do any dynamic linking at all -avoid-version do not add a version suffix if possi ...