Create Custom Operation

Last time in the post about Operation And OperaionQueue we discussed how to create and use Operation inside closure.

Using closure is an option if there is a simple task to do. However, if there is a more complex task it’s worth considering creating a custom operation class.

Operation is an open class introduced in iOS 2.0.

Let’s say you want to make a custom class to handle the same save operation as in the previous example.

class FileSaver: Operation {
    let fileName: String

    init(fileName: String) {
        self.fileName = fileName
    }

    override func main() {
        saveFile()
    }

    func saveFile()  {
        print(“File name: \(fileName))
    }
}

To execute code in the background you need to override the main function which will be executed in a background thread.

To check if it works to use the same code as previously. There is one difference that there is creating a new FileSaver instance instead of using closure.

let queue = OperationQueue()
let files = [“photosUrl”, “musicUrl”, “moviesUrl”]

for file in files {
    queue.addOperation(FileSaver(fileName: file))
}

Output

File name: photosUrl
File name: musicUrl
File name: moviesUrl