Calling an operation in a completion block without memory leak

I am creating an iOS application using swift.

Let's say I want to sort an array in another thread, which is the main thread. I can subclass NSOperation as follows:

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, the operation will never be released. How can I get a sorted array in a completion block (or elsewhere)?

I see a way. To create an object with only the property as array and pass that object to Operation, then I can get the array inside the object, but it certainly exists better.

thanks

+6
source share
3 answers
 operation.completionBlock = { [unowned operation] in operation.array // use your array } 
+7
source

There are several ways to handle this. Here is one:

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

This interrupts the save cycle at the end of the completion block.

+2
source

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

Source: https://habr.com/ru/post/983049/


All Articles