我正在使用
swift创建一个iOS应用程序.
假设我想在主线程的不同线程中对数组进行排序.我可以像这样继承NSOperation:
- import UIKit
- class Operation: NSOperation {
- var array:[Int]
- init(array:[Int]){
- self.array=array
- println("Operation init")
- }
- deinit{
- println("Operation deinit")
- }
- override func main() {
- for i in 0..<array.count{
- for j in 0..<array.count{
- if array[i]<array[j]{
- let k = array[i]
- array[i] = array[j]
- array[j] = k
- }
- }
- }
- }
- }
在我的ViewController中,我可以使用类似的东西:
- import UIKit
- class ViewController: UIViewController {
- override func viewDidLoad() {
- super.viewDidLoad()
- let array = [6,5,4,3,2,1]
- let operation = Operation(array: array)
- let operationQueue = NSOperationQueue()
- operationQueue.addOperation(operation)
- operation.completionBlock = {
- println("done")
- }
- }
- }
我的问题是:因为如果我在operation.completionBlock中调用operation.array,操作将永远不会被释放,如何在完成块(或其他地方)中检索已排序的数组?
我可以看到一种方式.这是创建一个只有数组作为属性的对象,并将此对象传递给Operation然后我将能够检索对象中的数组,但肯定它确实存在更好的方法.
谢谢
解决方法
- operation.completionBlock = { [unowned operation] in
- operation.array // use your array
- }