【Swift】三种多线程处理方式

前端之家收集整理的这篇文章主要介绍了【Swift】三种多线程处理方式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

刚开始学习swift语言,学习了网上的多线程构造方式写了一个小demo,源代码如下所示


import UIKit


/*图片总数

*/

let totalImg_COUNT : NSInteger = 20

/*下载图片地址

*/

let downloadImg_URL = "http://img10.360buyimg.com/imgzone/jfs/t2767/272/624097155/382343/b9a734bc/571da504N0e996b41.jpg"


let downloadImg_URL2 = "http://img10.360buyimg.com/imgzone/jfs/t2863/130/1039983507/438543/213230d3/5732c8daN2194ab7d.jpg"


var MainVC : ViewController = ViewController()


/*结构体 暂时不用

*/

//struct SomeStructure {

//

// static var MainVC : ViewController = ViewController()

//}


class ViewController: UIViewController

{

var activityIndicator : UIActivityIndicatorView = UIActivityIndicatorView()

var downloadcountlab : UILabel = UILabel()

var imgview : UIImageView = UIImageView()

var imgcount : NSInteger = 0


override func viewDidLoad() {

super.viewDidLoad()


MainVC = self

self.initview()

let btnnamearr = ["Thread","Operation","GCD","Clear"]


let methodarr = [#selector(testNSThread),#selector(testOperationQueue),#selector(testGCD(_:)),#selector(clear)]

for name in btnnamearr {

let Threadbtn:UIButton = UIButton(type:.System)

let index: Int? = btnnamearr.indexOf(name)

let floatvalue : CGFloat = CGFloat(index!)


Threadbtn.frame=CGRectMake(10,floatvalue * 50 + 100,100,35)

Threadbtn.setTitle(name,forState:UIControlState.Normal) //普通状态下的文字

Threadbtn.setTitle("触摸",forState:UIControlState.Highlighted) //触摸状态下的文字

let method : Selector = methodarr[index!]

Threadbtn.addTarget(self,action:method,forControlEvents:.TouchUpInside)

self.view.addSubview(Threadbtn);

}

}


override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

}

//1.NSThread 线程

func testNSThread(){

self.clear()

self.showisloading()

for _ in 0 ..< totalImg_COUNT{

/*

手动创建线程

*/

let thread1 = NSThread(target: self,selector: #selector(LoadImage),object: nil)

thread1.name="loading img"

thread1.start()

/*

方法创建线程

*/

// NSThread.detachNewThreadSelector(#selector(dlBigImage),toTarget: self,withObject: nil)


}

NSLog("thread success")

}

/*

加载图片

*/

func LoadImage(){

/*

时间较长操作

*/

var urlstring:String=String()

if MainVC.imgcount < 2 {

urlstring = downloadImg_URL2

}

else

{

urlstring = downloadImg_URL

}

let data = NSData (contentsOfURL: NSURL (string:urlstring)!)

let img = UIImage (data: data!)

if img != nil{


NSLog("currentThread %@", NSThread.currentThread())


dispatch_async(dispatch_get_main_queue(),{ () -> Void in

self.loadingsuccess(img!)

})


}

}

// 2.NSOperation 队列

func testOperationQueue(){


self.clear()

self.showisloading()

let queue = NSOperationQueue()


queue.maxConcurrentOperationCount = 5 ;

var operations = [MyOperation]()

for _ in 0 ..< totalImg_COUNT {

let myOperation = MyOperation()

myOperation.delegate = self

operations.append(myOperation)

}

queue.addOperations(operations,waitUntilFinished: false)

}

//​​3.GCD Grand Central Dispatch


func testGCD(button:UIButton){

NSLog("button tag is %d",button.tag)


self.clear()

self.showisloading()

for _ in 0 ..< totalImg_COUNT {

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),{ () -> Void in

/*

时间较长操作

*/

var urlstring:String=String()


if MainVC.imgcount < 2 {

urlstring = downloadImg_URL2

}


else

{

urlstring = downloadImg_URL

}

let data = NSData (contentsOfURL: NSURL (string:urlstring)!)

let img = UIImage (data: data!)

if img != nil{

dispatch_async(dispatch_get_main_queue(),{ () -> Void in

self.loadingsuccess(img!)

})

}

})


}

}

/*

初始化视图

*/

func initview()

{

self.imgview.frame=CGRectMake(150,150,100)

self.downloadcountlab.frame=CGRectMake(150,400,100)

self.view.addSubview(self.downloadcountlab)

self.activityIndicator = UIActivityIndicatorView(activityIndicatorStyle:

UIActivityIndicatorViewStyle.Gray)

self.activityIndicator.center = CGPointMake(50,70)

}

/*

清理图片与状态栏

*/

func clear(){

self.downloadcountlab.text = ""

for view in self.view.subviews {

if view .isKindOfClass(UIImageView) {

view.removeFromSuperview()

}

}

self.imgcount = 0

}

/*

正在加载

*/

func showisloading(){

self.activityIndicator.removeFromSuperview()

self.view.addSubview(self.activityIndicator)

self.activityIndicator.startAnimating()


}

/*

加载成功

*/

func loadingsuccess(img:UIImage){

self.imgcount=self.imgcount + 1

self.downloadcountlab.text=String(self.imgcount)


let y :CGFloat = CGFloat(self.imgcount/3*50)

let imgview : UIImageView = UIImageView()

imgview.frame = CGRectMake(150 + CGFloat(self.imgcount%3) * 50.0,50 + y,40,40)

imgview.image = img

self.view.addSubview(imgview)

NSLog("self.imgcount is %d",self.imgcount)

if self.imgcount == totalImg_COUNT {

self.activityIndicator.stopAnimating()


self.activityIndicator.removeFromSuperview()


}

}

}


/*

我的队列类

*/


class MyOperation: NSOperation {


weak var delegate:ViewController?

override func start() {

super.start()

}

override func main(){

/*

时间较长操作

*/

var urlstring:String=String()

if MainVC.imgcount < 2 {

urlstring = downloadImg_URL2

}

else

{

urlstring = downloadImg_URL

}

let data = NSData (contentsOfURL: NSURL (string:urlstring)!)

let img = UIImage (data: data!)

if img != nil{

dispatch_async(dispatch_get_main_queue(),{ () -> Void in

MainVC.loadingsuccess(img!)

})

}

}

}

原文链接:https://www.f2er.com/swift/323790.html

猜你在找的Swift相关文章