Swift 멀티스레드 - 운영 대기열 NSOperation

2069 단어
작업 대기열 NSOperation
NSOperation에는 세 가지 유용한 볼 속성이 있습니다.finished, cancelled,ready는 작업이 완료되면finisher는true로 설정됩니다. 작업이 취소되면cancelled는true로 설정됩니다. 준비가 완료되면 ready는true로 설정됩니다.
3.1
//    
let queue = NSOperationQueue()


@IBAction func downloadImages(sender: UIButton) {
   
    queue.addOperationWithBlock { () -> Void in
        let image1 = Downloader.downloadImageWithURL(self.imageUrls[0])
        
        NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
            self.imageViewArr[0].image = image1
        })
    }
    
    // 1. Create a NSBlockOperation object
    
    let op2 = NSBlockOperation { () -> Void in
        let image2 = Downloader.downloadImageWithURL(self.imageUrls[1])
        
        NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
            self.imageViewArr[1].image = image2
        })
    }
    
    // 2. Set finish callback
    op2.completionBlock = { print("image2 downloaded") }
    
    // 3. Add to operation queue manually
//        queue.addOperation(op2)
    
    
    let op3 = NSBlockOperation { () -> Void in
        let image3 = Downloader.downloadImageWithURL(self.imageUrls[2])
        
        NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
            self.imageViewArr[2].image = image3
        })
    }
    
    op3.completionBlock = { print("image3 cancelled: \(op3.cancelled)") }
    

    
    let op4 = NSBlockOperation { () -> Void in
        let image4 = Downloader.downloadImageWithURL(self.imageUrls[3])
        
        NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
            self.imageViewArr[3].image = image4
        })
    }
    
    op4.completionBlock = { print("image4 downloaded") }
    

    //     
    op3.addDependency(op4)
    op2.addDependency(op3)
    
    queue.addOperation(op4)
    queue.addOperation(op3)
    queue.addOperation(op2)

    
}



@IBAction func cancelDown(sender: UIButton) {
    
    queue.cancelAllOperations()
    
}

좋은 웹페이지 즐겨찾기