前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >IOS Operation实现多线程

IOS Operation实现多线程

作者头像
用户5760343
发布2019-07-08 13:02:03
4570
发布2019-07-08 13:02:03
举报
文章被收录于专栏:sktj
代码语言:javascript
复制
 1 var topImageView = UIImageView()
 2 var footImageView = UIImageView()
 3 override func viewDidLoad() {
 4 super.viewDidLoad()
 5 // Do any additional setup after loading the view,
 typically from a nib.
 6 topImageView = UIImageView(frame:CGRect(x:0,
 y:0, width:320, height:280))
 7 self.view.addSubview(topImageView)
 8
 9 footImageView = UIImageView(frame:CGRect(x:0,
 y:280, width:320, height:290))
 10 self.view.addSubview(footImageView)
 11
 12 let downloadA = getOperation(name:”下载线程 A”,
 imageUrl:
 “http://images.apple.com/v/watch/k/images/overview/watch_03_large.jpg”,
 isTopOne:true)
 13
 14 let downloadB = getOperation(name:”下载线程B”,
 imageUrl:“http://images.apple.com/v/watch/k/images/overview/watch_05_large.jpg”,
 isTopOne:false)
 15
 16 let queue = OperationQueue()
 17 queue.maxConcurrentOperationCount = 1
 18 queue.addOperation(downloadA)
 19 queue.addOperation(downloadB)
 20
 21 for operation in queue.operations{
 22 print(“Operation名称:”+operation.name!)
 23 }
 24 }
 25 func getOperation(name:String, imageUrl:String,
 isTopOne:Bool) -> BlockOperation{
 26 let download = BlockOperation(block:{_ in
 27 let url = URL(string:imageUrl)
 28 var data:Data!
 29 do{
 30 Thread.sleep(forTimeInterval:1.0)
 31 try data = Data(contentsOf:url!)
 32 let image = UIImage(data:data)
 33 if isTopOne{
 34 self.perform(#selector(ViewController.showTopImage),
 on:Thread.main, with: image, waitUntilDone:true)
 35 }
 36 else{
 37
 self.perform(#selector(ViewController.showFootImage), on:
 Thread.main, with: image, waitUntilDone:true)
 38 }
 39 }catch{
 40 print(“下载图片失败。”)
 41 }
 42 })
 43 download.name = name
 44 return download
 45 }
 46 func showTopImage(image:UIImage){
 47 self.topImageView.image = image
 48 }
 49
 50 func showFootImage(image:UIImage){
 51 self.footImageView.image = image
 52 }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019.06.10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档