前言
最近看了一些Swift关于封装异步操作过程的文章,比如RxSwift,RAC等等,因为回调地狱我自己也写过,很有感触,于是就翻出了Promise来研究学习一下。现将自己的一些收获分享一下,有错误欢迎大家多多指教。
目录
- 1.PromiseKit简介
- 2.PromiseKit安装和使用
- 3.PromiseKit主要函数的使用方法
- 4.PromiseKit的源码解析
- 5.使用PromiseKit优雅的处理回调地狱
一.PromiseKit简介
PromiseKit是iOS/OS X 中一个用来出来异步编程框架。这个框架是由Max Howell(Mac下Homebrew的作者,传说中因为”不会”写反转二叉树而没有拿到Google offer)大神级人物开发出来的。
在PromiseKit中,最重要的一个概念就是Promise的概念,Promise是异步操作后的future的一个值。
A promise represents the future value of an asynchronous task.
A promise is an object that wraps an asynchronous task
Promise也是一个包装着异步操作的一个对象。使用PromiseKit,能够编写出整洁,有序的代码,逻辑简单的,将Promise作为参数,模块化的从一个异步任务到下一个异步任务中去。用PromiseKit写出的代码就是这样:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
[self login].then(^{ // our login method wrapped an async task in a promise return [API fetchData]; }).then(^(NSArray *fetchedData){ // our API class wraps our API and returns promises // fetchedData returned a promise that resolves with an array of data self.datasource = fetchedData; [self.tableView reloadData]; }).catch(^(NSError *error){ // any errors in any of the above promises land here [[[UIAlertView alloc] init…] show]; }); |
PromiseKit就是用来干净简洁的代码,来解决异步操作,和奇怪的错误处理回调的。它将异步操作变成了链式的调用,简单的错误处理方式。
PromiseKit里面目前有2个类,一个是Promise<T>(Swift),一个是AnyPromise(Objective-C),2者的区别就在2种语言的特性上,Promise<T>是定义精确严格的,AnyPromise是定义宽松,灵活,动态的。
在异步编程中,有一个最最典型的例子就是回调地狱CallBack hell,要是处理的不优雅,就会出现下图这样:
上图的代码是真实存在的,也是朋友告诉我的,来自快的的代码,当然现在人家肯定改掉了。虽然这种代码看着像这样:
代码虽然看上去不优雅,功能都是正确的,但是这种代码基本大家都自己写过,我自己也写过很多。今天就让我们动起手来,用PromiseKit来优雅的处理掉Callback hell吧。
二.PromiseKit安装和使用
1.下载安装CocoaPods
在墙外的安装步骤:
在Terminal里面输入
1 |
sudo gem install cocoapods && pod setup |
大多数在墙内的同学应该看如下步骤了:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
//移除原有的墙外Ruby 默认源 $ gem sources --remove https://rubygems.org/ //添加现有的墙内的淘宝源 $ gem sources -a https://ruby.taobao.org/ //验证新源是否替换成功 $ gem sources -l //下载安装cocoapods // OS 10.11之前 $ sudo gem install cocoapods //mark:OS 升级 OS X EL Capitan 后命令应该为: $ sudo gem install -n /usr/local/bin cocoapods //设置cocoapods $ pod setup |
1 |
$ touch Podfile && open -e Podfile |
此时会打开TextEdit,然后输入一下命令:
1 2 3 4 5 |
platform:ios, ‘7.0’ target 'PromisekitDemo' do //由于最新版cocoapods的要求,所以必须加入这句话 pod 'PromiseKit' end |
Tips:感谢qinfensky大神提醒,其实这里也可以用init命令
Podfile是CocoaPods的特殊文件,在其中可以列入在项目中想要使用的开源库,若想创建Podfile,有2种方法:
1.在项目目录中创建空文本文件,命名为Podfile
2.或者可以再项目目录中运行“$ pod init “,来创建功能性文件(终端中输入cd 文件夹地址,然后再输入 pod init)
两种方法都可以创建Podfile,使用你最喜欢使用的方法
3.安装PromiseKit
1 |
$ pod install |
安装完成之后,退出终端,打开新生成的.xcworkspace文件即可
三.PromiseKit主要函数的使用方法
- then
经常我们会写出这样的代码:
egate = self;
self.state = state;
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 1) {
[self.state do];
}
}
|