iOS Developer Library

Developer

Foundation Framework Reference NSOperation Class Reference

Options
Deployment Target:

On This Page
Language:

NSOperation

The NSOperation class is an abstract class you use to encapsulate the code and data associated with a single task. Because it is abstract, you do not use this class directly but instead subclass or use one of the system-defined subclasses (NSInvocationOperation or NSBlockOperation) to perform the actual task. Despite being abstract, the base implementation of NSOperation does include significant logic to coordinate the safe execution of your task. The presence of this built-in logic allows you to focus on the actual implementation of your task, rather than on the glue code needed to ensure it works correctly with other system objects. More...

Conforms To


Import Statement


import Foundation @import Foundation;

Availability


Available in iOS 2.0 and later.
  • init init Available in iOS 2.0 through iOS 7.1

    Returns an initialized NSOperation object.

    Declaration

    Objective-C

    - (id)init

    Return Value

    The initialized NSOperation object.

    Discussion

    Your custom subclasses must call this method. The default implementation initializes the object’s instance variables and prepares it for use. This method runs on the current thread—that is, the thread you use to allocate the operation object.

    Import Statement

    Availability

    Available in iOS 2.0 through iOS 7.1.

  • Begins the execution of the operation.

    Declaration

    Swift

    func start()

    Objective-C

    - (void)start

    Discussion

    The default implementation of this method updates the execution state of the operation and calls the receiver’s main method. This method also performs several checks to ensure that the operation can actually run. For example, if the receiver was cancelled or is already finished, this method simply returns without calling main. (In OS X v10.5, this method throws an exception if the operation is already finished.) If the operation is currently executing or is not ready to execute, this method throws an NSInvalidArgumentException exception. In OS X v10.5, this method catches and ignores any exceptions thrown by your main method automatically. In OS X v10.6 and later, exceptions are allowed to propagate beyond this method. You should never allow exceptions to propagate out of your main method.

    If you are implementing a concurrent operation, you must override this method and use it to initiate your operation. Your custom implementation must not call super at any time. In addition to configuring the execution environment for your task, your implementation of this method must also track the state of the operation and provide appropriate state transitions. When the operation executes and subsequently finishes its work, it should generate KVO notifications for the isExecuting and isFinished key paths respectively. For more information about manually generating KVO notifications, see Key-Value Observing Programming Guide.

    You can call this method explicitly if you want to execute your operations manually. However, it is a programmer error to call this method on an operation object that is already in an operation queue or to queue the operation after calling this method. Once you add an operation object to a queue, the queue assumes all responsibility for it.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Performs the receiver’s non-concurrent task.

    Declaration

    Swift

    func main()

    Objective-C

    - (void)main

    Discussion

    The default implementation of this method does nothing. You should override this method to perform the desired task. In your implementation, do not invoke super.

    If you are implementing a concurrent operation, you are not required to override this method but may do so if you plan to call it from your custom start method.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

    See Also

    – start

  • The block to execute after the operation’s main task is completed.

    Declaration

    Swift

    var completionBlock: (() -> Void)?

    Objective-C

    @property(copy) void (^completionBlock)(void)

    Discussion

    The completion block takes no parameters and has no return value.

    The exact execution context for your completion block is not guaranteed but is typically a secondary thread. Therefore, you should not use this block to do any work that requires a very specific execution context. Instead, you should shunt that work to your application’s main thread or to the specific thread that is capable of doing it. For example, if you have a custom thread for coordinating the completion of the operation, you could use the completion block to ping that thread.

    The completion block you provide is executed when the value in the finished property changes to YEStrue. Because the completion block executes after the operation indicates it has finished its task, you must not use a completion block to queue additional work considered to be part of that task. An operation object whose finished property contains the value YEStrue must be done with all of its task-related work by definition. The completion block should be used to notify interested objects that the work is complete or perform other tasks that might be related to, but not part of, the operation’s actual task.

    A finished operation may finish either because it was cancelled or because it successfully completed its task. You should take that fact into account when writing your block code. Similarly, you should not make any assumptions about the successful completion of dependent operations, which may themselves have been cancelled.

    In iOS 8 and later and OS X v10.10 and later, this property is set to nil after the completion block begins executing.

    Import Statement

    import Foundation

    Availability

    Available in iOS 4.0 and later.

  • Advises the operation object that it should stop executing its task.

    Declaration

    Swift

    func cancel()

    Objective-C

    - (void)cancel

    Discussion

    This method does not force your operation code to stop. Instead, it updates the object’s internal flags to reflect the change in state. If the operation has already finished executing, this method has no effect. Canceling an operation that is currently in an operation queue, but not yet executing, makes it possible to remove the operation from the queue sooner than usual.

    In OS X v10.6 and later, if an operation is in a queue but waiting on unfinished dependent operations, those operations are subsequently ignored. Because it is already cancelled, this behavior allows the operation queue to call the operation’s start method sooner and clear the object out of the queue. If you cancel an operation that is not in a queue, this method immediately marks the object as finished. In each case, marking the object as ready or finished results in the generation of the appropriate KVO notifications.

    In versions of OS X prior to 10.6, an operation object remains in the queue until all of its dependencies are removed through the normal processes. Thus, the operation must wait until all of its dependent operations finish executing or are themselves cancelled and have their start method called.

    For more information on what you must do in your operation objects to support cancellation, see Responding to the Cancel Command.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

    See Also

    cancelled

  • cancelled cancelled Property

    A Boolean value indicating whether the operation has been cancelled (read-only)

    Declaration

    Swift

    var cancelled: Bool { get }

    Objective-C

    @property(readonly, getter=isCancelled) BOOL cancelled

    Discussion

    The default value of this property is NOfalse. Calling the cancel method of this object sets the value of this property to YEStrue. Once canceled, an operation must move to the finished state.

    Canceling an operation does not actively stop the receiver’s code from executing. An operation object is responsible for calling this method periodically and stopping itself if the method returns YEStrue.

    You should always check the value of this property before doing any work towards accomplishing the operation’s task, which typically means checking it at the beginning of your custom main method. It is possible for an operation to be cancelled before it begins executing or at any time while it is executing. Therefore, checking the value at the beginning of your main method (and periodically throughout that method) lets you exit as quickly as possible when an operation is cancelled.

    Import Statement

    import Foundation

    Availability

    Available in iOS 8.0 and later.

    See Also

    – cancel

  • executing executing Property

    A Boolean value indicating whether the operation is currently executing. (read-only)

    Declaration

    Swift

    var executing: Bool { get }

    Objective-C

    @property(readonly, getter=isExecuting) BOOL executing

    Discussion

    The value of this property is YEStrue if the operation is currently executing its main task or NOfalse if it is not.

    When implementing a concurrent operation object, you must override the implementation of this property so that you can return the execution state of your operation. In your custom implementation, you must generate KVO notifications for the isExecuting key path whenever the execution state of your operation object changes. For more information about manually generating KVO notifications, see Key-Value Observing Programming Guide.

    You do not need to reimplement this property for nonconcurrent operations.

    Import Statement

    import Foundation

    Availability

    Available in iOS 8.0 and later.

  • finished finished Property

    A Boolean value indicating whether the operation has finished executing its task. (read-only)

    Declaration

    Swift

    var finished: Bool { get }

    Objective-C

    @property(readonly, getter=isFinished) BOOL finished

    Discussion

    The value of this property is YEStrue if the operation has finished its main task or NOfalse if it is executing that task or has not yet started it.

    When implementing a concurrent operation object, you must override the implementation of this property so that you can return the finished state of your operation. In your custom implementation, you must generate KVO notifications for the isFinished key path whenever the finished state of your operation object changes. For more information about manually generating KVO notifications, see Key-Value Observing Programming Guide.

    You do not need to reimplement this property for nonconcurrent operations.

    Import Statement

    import Foundation

    Availability

    Available in iOS 8.0 and later.

  • A Boolean value indicating whether the operation executes its task asynchronously. (read-only)

    Declaration

    Swift

    var concurrent: Bool { get }

    Objective-C

    @property(readonly, getter=isConcurrent) BOOL concurrent

    Discussion

    Use the asynchronous property instead.

    The value of this property is YEStrue for operations that run asynchronously with respect to the current thread or NOfalse for operations that run synchronously on the current thread. The default value of this property is NOfalse.

    In OS X v10.6 and later, operation queues ignore the value in this property and always start operations on a separate thread.

    Import Statement

    import Foundation

    Availability

    Available in iOS 8.0 and later.

  • A Boolean value indicating whether the operation executes its task asynchronously. (read-only)

    Declaration

    Swift

    var asynchronous: Bool { get }

    Objective-C

    @property(readonly, getter=isAsynchronous) BOOL asynchronous

    Discussion

    The value of this property is YEStrue for operations that run asynchronously with respect to the current thread or NOfalse for operations that run synchronously on the current thread. The default value of this property is NOfalse.

    When implementing an asynchronous operation object, you must implement this property and return YEStrue. For more information about how to implement an asynchronous operation, see Asynchronous Versus Synchronous Operations.

    Import Statement

    import Foundation

    Availability

    Available in iOS 7.0 and later.

  • ready ready Property

    A Boolean value indicating whether the operation can be performed now. (read-only)

    Declaration

    Swift

    var ready: Bool { get }

    Objective-C

    @property(readonly, getter=isReady) BOOL ready

    Discussion

    The readiness of operations is determined by their dependencies on other operations and potentially by custom conditions that you define. The NSOperation class manages dependencies on other operations and reports the readiness of the receiver based on those dependencies.

    If you want to use custom conditions to define the readiness of your operation object, reimplement this property and return a value that accurately reflects the readiness of the receiver. If you do so, your custom implementation must get the default property value from super and incorporate that readiness value into the new value of the property. In your custom implementation, you must generate KVO notifications for the isReady key path whenever the ready state of your operation object changes. For more information about generating KVO notifications, see Key-Value Observing Programming Guide.

    Import Statement

    import Foundation

    Availability

    Available in iOS 8.0 and later.

    See Also

    dependencies

  • name name Property

    The name of the operation.

    Declaration

    Swift

    var name: String?

    Objective-C

    @property(copy) NSString *name

    Discussion

    Assign a name to the operation object to help identify it during debugging.

    Import Statement

    import Foundation

    Availability

    Available in iOS 8.0 and later.

  • Makes the receiver dependent on the completion of the specified operation.

    Declaration

    Swift

    func addDependency(_ operation: NSOperation)

    Objective-C

    - (void)addDependency:(NSOperation *)operation

    Parameters

    operation

    The operation on which the receiver should depend. The same dependency should not be added more than once to the receiver, and the results of doing so are undefined.

    Discussion

    The receiver is not considered ready to execute until all of its dependent operations have finished executing. If the receiver is already executing its task, adding dependencies has no practical effect. This method may change the isReady and dependencies properties of the receiver.

    It is a programmer error to create any circular dependencies among a set of operations. Doing so can cause a deadlock among the operations and may freeze your program.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Removes the receiver’s dependence on the specified operation.

    Declaration

    Swift

    func removeDependency(_ operation: NSOperation)

    Objective-C

    - (void)removeDependency:(NSOperation *)operation

    Parameters

    operation

    The dependent operation to be removed from the receiver.

    Discussion

    This method may change the isReady and dependencies properties of the receiver.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • An array of the operation objects that must finish executing before the current object can begin executing. (read-only)

    Declaration

    Swift

    var dependencies: [AnyObject] { get }

    Objective-C

    @property(readonly, copy) NSArray *dependencies

    Discussion

    This property contains an array of NSOperation objects. To add an object to this array, use the addDependency: method.

    An operation object must not execute until all of its dependent operations finish executing. Operations are not removed from this dependency list as they finish executing. You can use this list to track all dependent operations, including those that have already finished executing. The only way to remove an operation from this list is to use the removeDependency: method.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • The relative amount of importance for granting system resources to the operation.

    Declaration

    Swift

    var qualityOfService: NSQualityOfService

    Objective-C

    @property NSQualityOfService qualityOfService

    Discussion

    Service levels affect the priority with which an operation object is given access to system resources such as CPU time, network resources, disk resources, and so on. Operations with a higher quality of service level are given greater priority over system resources so that they may perform their task more quickly. You use service levels to ensure that operations responding to explicit user requests are given priority over less critical work.

    This property reflects the minimum service level needed to execute the operation effectively. The default value of this property is NSOperationQualityOfServiceBackground and you should leave that value in place whenever possible. When changing the service level, use the minimum level that is appropriate for executing the corresponding task. For example, if the user initiates a task and is waiting for it to finish, assign the value NSOperationQualityOfServiceUserInitiated to this property. The system may give the operation a higher service level to the operation if the resources are available to do so.

    Import Statement

    import Foundation

    Availability

    Available in iOS 8.0 and later.

  • threadPriority threadPriority (iOS 8.0) Property

    The thread priority to use when executing the operation

    Declaration

    Swift

    var threadPriority: Double

    Objective-C

    @property double threadPriority

    Discussion

    The value in this property is a floating-point number in the range 0.0 to 1.0, where 1.0 is the highest priority. The default thread priority is 0.5.

    The value you specify is mapped to the operating system’s priority values. The specified thread priority is applied to the thread only while the operation’s main method is executing. It is not applied while the operation’s completion block is executing. For a concurrent operation in which you create your own thread, you must set the thread priority yourself in your custom start method and reset the original priority when the operation is finished.

    Import Statement

    import Foundation

    Availability

    Available in iOS 4.0 and later.

    Deprecated in iOS 8.0.

    See Also

    threadPriority

  • The execution priority of the operation in an operation queue.

    Declaration

    Swift

    var queuePriority: NSOperationQueuePriority

    Objective-C

    @property NSOperationQueuePriority queuePriority

    Discussion

    This property contains the relative priority of the operation. This value is used to influence the order in which operations are dequeued and executed. The returned value always corresponds to one of the predefined constants. (For a list of valid values, see NSOperationQueuePriority.) If no priority is explicitly set, this method returns NSOperationQueuePriorityNormal.

    You should use priority values only as needed to classify the relative priority of non-dependent operations. Priority values should not be used to implement dependency management among different operation objects. If you need to establish dependencies between operations, use the addDependency: method instead.

    If you attempt to specify a priority value that does not match one of the defined constants, the operation object automatically adjusts the value you specify towards the NSOperationQueuePriorityNormal priority, stopping at the first valid constant value. For example, if you specified the value -10, the operation would adjust that value to match the NSOperationQueuePriorityVeryLow constant. Similarly, if you specified +10, this operation would adjust the value to match the NSOperationQueuePriorityVeryHigh constant.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Blocks execution of the current thread until the operation object finishes its task.

    Declaration

    Swift

    func waitUntilFinished()

    Objective-C

    - (void)waitUntilFinished

    Discussion

    An operation object must never call this method on itself and should avoid calling it on any operations submitted to the same operation queue as itself. Doing so can cause the operation to deadlock. Instead, other parts of your app may call this method as needed to prevent other tasks from completing until the target operation object finishes. It is generally safe to call this method on an operation that is in a different operation queue, although it is still possible to create deadlocks if each operation waits on the other.

    A typical use for this method would be to call it from the code that created the operation in the first place. After submitting the operation to a queue, you would call this method to wait until that operation finished executing.

    Import Statement

    import Foundation

    Availability

    Available in iOS 4.0 and later.

  • These constants let you prioritize the order in which operations execute.

    Declaration

    Swift

    enum NSOperationQueuePriority : Int { case VeryLow case Low case Normal case High case VeryHigh }

    Objective-C

    typedef enum : NSInteger { NSOperationQueuePriorityVeryLow = -8, NSOperationQueuePriorityLow = -4, NSOperationQueuePriorityNormal = 0, NSOperationQueuePriorityHigh = 4, NSOperationQueuePriorityVeryHigh = 8 } NSOperationQueuePriority;

    Constants

    • VeryLow

      NSOperationQueuePriorityVeryLow

      Operations receive very low priority for execution.

      Available in iOS 2.0 and later.

    • Low

      NSOperationQueuePriorityLow

      Operations receive low priority for execution.

      Available in iOS 2.0 and later.

    • Normal

      NSOperationQueuePriorityNormal

      Operations receive the normal priority for execution.

      Available in iOS 2.0 and later.

    • High

      NSOperationQueuePriorityHigh

      Operations receive high priority for execution.

      Available in iOS 2.0 and later.

    • VeryHigh

      NSOperationQueuePriorityVeryHigh

      Operations receive very high priority for execution.

      Available in iOS 2.0 and later.

    Discussion

    You can use these constants to specify the relative ordering of operations that are waiting to be started in an operation queue. You should always use these constants (and not the defined value) for determining priority.

    Import Statement

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Constants indicating the priority with which system resources are given to the operation

    Declaration

    Objective-C

    #define NSOperationQualityOfService NSQualityOfService #define NSOperationQualityOfServiceUserInteractive NSQualityOfServiceUserInteractive #define NSOperationQualityOfServiceUserInitiated NSQualityOfServiceUserInitiated #define NSOperationQualityOfServiceUtility NSQualityOfServiceUtility #define NSOperationQualityOfServiceBackground NSQualityOfServiceBackground

    Constants

    • NSOperationQualityOfService

      NSOperationQualityOfService

      The overall type for quality-of-service constants. Do not use this macro as a value when specifying the quality of service.

      Available in iOS 8.0 and later.

    • NSOperationQualityOfServiceUserInteractive

      NSOperationQualityOfServiceUserInteractive

      The operation corresponds to a graphically interactive task, involving scrolling or animation in some form. Because they are user interactive, operations with this service level are given the highest priority for any needed system resources.

      Available in iOS 8.0 and later.

    • NSOperationQualityOfServiceUserInitiated

      NSOperationQualityOfServiceUserInitiated

      The operation corresponds to a task that the user initiated. Tasks with this service level are given a relatively high priority for system resources because they were initiated by the user and therefore correspond to work the user wants done soon.

      Available in iOS 8.0 and later.

    • NSOperationQualityOfServiceUtility

      NSOperationQualityOfServiceUtility

      The operation corresponds to tasks initiated by the app but reflecting relatively important work being done on behalf of the user. Tasks with this service level are given a medium priority for system resources.

      Available in iOS 8.0 and later.

    • NSOperationQualityOfServiceBackground

      NSOperationQualityOfServiceBackground

      The operation corresponds to tasks that are initiated by the app and represent noncritical tasks. Operations with this priority are given the lowest priority for system resources.

      Available in iOS 8.0 and later.

    Import Statement