您的位置:首页 > 移动开发 > IOS开发

iOS 线程库 promisekit

2015-06-05 15:59 375 查看
iOS 线程操作库 PromiseKit

官网:http://promisekit.org/

github

https://github.com/mxcl/PromiseKit/tree/master
一:安装

第一种方式使用 cocoaPods
直接安装方式:下载PromiseKit 先如图文件导入你的项目



然后,再导入 Chuzzle.h,m 文件 两个文件 下载:https://github.com/mxcl/ChuzzleKit

二:使用

我们演示一个异步下载图片,然后加载到 imageView上;

我们传统的GCD做法:



//创建imageView
    UIImageView *theImageV = [[UIImageView alloc]initWithFrame:CGRectMake(50, 100, 200, 200)];
    theImageV.backgroundColor = [UIColor grayColor];
    [self.view addSubview:theImageV];
    
    
    //图片链接
    NSString *imageURL = @"http://f.hiphotos baidu

.com/image/w%3D2048/sign=5545a5d7af4bd11304cdb0326e97a60f/2f738bd4b31c87013c5bf342257f9e2f0608ffa1.jpg";
    
    //异步加载图片并显示
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]];
        
        //回到主线程刷新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            theImageV.image = [[UIImage alloc]initWithData:data];
        });

    });




使用 Promise的做法



//使用Promise
    dispatch_promise(^{
        
        
        NSString *imageURL = @"http://g.hiphotos baidu

.com/image/h%3D1050%3Bcrop%3D0%2C0%2C1680%2C1050/sign=9a06c1578fb1cb1321693813e8646d2d/1b4c510fd9f9d72acef7baa5d62a2834359bbbf3.jpg";
        return imageURL;
        
        
    }).then(^(NSString *url){
        
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
        return data;
        
    }).then(^(NSData *data){
        
        theImageV.image = [[UIImage alloc]initWithData:data];

    });




三:使用 PromiseKit+UIKit :

#import "PromiseKit+UIKit.h"




UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"You Didn’t Save!"
                                                    message:@"You will lose changes."
                                                   delegate:nil
                                          cancelButtonTitle:@"Cancel"
                                          otherButtonTitles:@"Lose Changes", @"Panic", nil];
    
    alert.promise.then(^(NSNumber *dismissedIndex){
        
        NSLog(@"clock index : %@",dismissedIndex);
        
    });






四:从上面的两个例子,我们可以看出 PromistKit ,可以理解为每一次操作都是一个 Promise 即承诺,每一个承诺都将有一个结果,所以就有了 .then.then,,,.cath

这种方式的写法,线程更安全,代码更友好



参考:http://promisekit.org/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: