iOS 线程操作库 PromiseKit
iOS 线程操作库 PromiseKit
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
这种方式的写法,线程更安全,代码更友好
分类:
开源类
标签:
promise
, PromiseKit
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具