7

I am creating an iOS app using swift.

Let's say I want to sort an array in a different thread that the main thread. I can subclass NSOperation like that :

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
                }
            }
        }
    }

}

In my ViewController, I can use something like :

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")
        }
    }
}

My question is :since if I call operation.array in operation.completionBlock, operation will never be released, How can I retrieve the sorted array in the completion block (or elsewhere)?

I can see a way. It's to create an object with just the array as property and pass this object to Operation then I will be able to retrieve the array within the object but for sure it does exist a better way.

Thank you

soling
  • 541
  • 6
  • 20

3 Answers3

9
operation.completionBlock = { [unowned operation] in
    operation.array // use your array
}
kean
  • 1,561
  • 14
  • 22
3

There are several ways you could handle this. Here's one:

operation.completionBlock = {
    println("done")
    // other stuff involving operation.array
    operation.completionBlock = nil
}

This breaks the retain cycle at the end of the completion block.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
0

operation.array

 func testSortArray() {
    let array = [6,5,4,3,2,1]
    let operation = Operation(array: array)
    let operationQueue = NSOperationQueue()
    operationQueue.addOperation(operation)
    operation.completionBlock = {
        println("done \(operation.array)")
    }
}
iOSfleer
  • 408
  • 6
  • 20