Skip to content

Instantly share code, notes, and snippets.

@alexdrone
Last active October 20, 2015 18:17
Show Gist options
  • Save alexdrone/0acd62902d69238c0389 to your computer and use it in GitHub Desktop.
Save alexdrone/0acd62902d69238c0389 to your computer and use it in GitHub Desktop.
//
// AsynchronousOperation.swift
// Primer
//
// Created by Alex Usbergo on 18/10/15.
// Copyright © 2015 Alex Usbergo. All rights reserved.
//
import Foundation
@objc public class AsynchronousOperationContext: NSObject {
///The user info for the operation
@objc public var userInfo = [String: AnyObject]()
@objc public var error: NSError?
}
///Base class for a asynchronous operation.
///Subclasses are expected to override the 'execute' function and call
///the function 'finish' when they're done with their task
@objc public class AsynchronousOperation: NSOperation {
///The operation context
public typealias Context = AsynchronousOperationContext
//property overrides
override public var asynchronous: Bool { return true }
override public var concurrent: Bool { return true }
override public var executing: Bool { return __executing }
override public var finished: Bool { return __finished }
///The context for this operation.
///Useful to pass data from/to dependant operations
@objc public let context: Context?
init(withContext context: Context? = nil) {
self.context = context
}
//__ to avoid name clash with the superclass
private var __executing = false {
willSet { willChangeValueForKey("isExecuting") }
didSet { didChangeValueForKey("isExecuting") }
}
private var __finished = false {
willSet { willChangeValueForKey("isFinished") }
didSet { didChangeValueForKey("isFinished") }
}
override public func start() {
__executing = true
execute()
}
///Subclasses are expected to override the 'execute' function and call
///the function 'finish' when they're done with their task
@objc public func execute() {
fatalError("Your subclass must override this")
}
///This function should be called inside 'execute' when the task for this
///operation is completed
@objc public func finish() {
__executing = false
__finished = true
}
}
///Shorthand for creating an asynchronous operation with a given block
///Remember to call the 'finish' function on the operation within the block passed as argument
@objc public class AsynchronousBlockOperation: AsynchronousOperation {
///The operation execution block
public typealias ExecutionBlock = ((operation: AsynchronousBlockOperation, context: Context?) -> Void)
@objc public let block: ExecutionBlock
init(withContext context: Context?, block: ExecutionBlock) {
self.block = block
super.init(withContext: context)
}
public override func execute() {
self.block(operation: self, context: self.context)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment