iOS Developer Library — Pre-Release

Developer

Foundation Framework Reference NSOperationQueue Class Reference

Options
Deployment Target:

On This Page
Language:

NSOperationQueue

Inheritance


Conforms To


Import Statement


Swift

import Foundation

Objective-C

@import Foundation;

Availability


Available in iOS 2.0 and later.

The NSOperationQueue class regulates the execution of a set of NSOperation objects. After being added to a queue, an operation remains in that queue until it is explicitly canceled or finishes executing its task. Operations within the queue (but not yet executing) are themselves organized according to priority levels and inter-operation object dependencies and are executed accordingly. An application may create multiple operation queues and submit operations to any of them.

Inter-operation dependencies provide an absolute execution order for operations, even if those operations are located in different operation queues. An operation object is not considered ready to execute until all of its dependent operations have finished executing. For operations that are ready to execute, the operation queue always executes the one with the highest priority relative to the other ready operations. For details on how to set priority levels and dependencies, see NSOperation Class Reference.

You cannot directly remove an operation from a queue after it has been added. An operation remains in its queue until it reports that it is finished with its task. Finishing its task does not necessarily mean that the operation performed that task to completion. An operation can also be canceled. Canceling an operation object leaves the object in the queue but notifies the object that it should abort its task as quickly as possible. For currently executing operations, this means that the operation object’s work code must check the cancellation state, stop what it is doing, and mark itself as finished. For operations that are queued but not yet executing, the queue must still call the operation object’s start method so that it can processes the cancellation event and mark itself as finished.

Operation queues usually provide the threads used to run their operations. Operation queues use the libdispatch library (also known as Grand Central Dispatch) to initiate the execution of their operations. As a result, operations are always executed on a separate thread, regardless of whether they are designated as asynchronous or synchronous operations.

For more information about using operation queues, see Concurrency Programming Guide.

KVO-Compliant Properties

The NSOperationQueue class is key-value coding (KVC) and key-value observing (KVO) compliant. You can observe these properties as desired to control other parts of your application. To observe the properties, use the following key paths::

  • operations - read-only

  • operationCount - read-only

  • maxConcurrentOperationCount - readable and writable

  • suspended - readable and writable

  • name - readable and writable

Although you can attach observers to these properties, you should not use Cocoa bindings to bind them to elements of your application’s user interface. Code associated with your user interface typically must execute only in your application’s main thread. However, KVO notifications associated with an operation queue may occur in any thread.

For more information about key-value observing and how to attach observers to an object, see Key-Value Observing Programming Guide.

Multicore Considerations

It is safe to use a single NSOperationQueue object from multiple threads without creating additional locks to synchronize access to that object.

Additional Operation Queue Behaviors

An operation queue executes its queued operation objects based on their priority and readiness. If all of the queued operation objects have the same priority and are ready to execute when they are put in the queue—that is, their isReady method returns YEStrue—they are executed in the order in which they were submitted to the queue. However, you should never rely on queue semantics to ensure a specific execution order of operation objects. Changes in the readiness of an operation can change the resulting execution order. If you need operations to execute in a specific order, use operation-level dependencies as defined by the NSOperation class.

  • Returns the operation queue that launched the current operation.

    Declaration

    Swift

    class func currentQueue() -> NSOperationQueue?

    Objective-C

    + (NSOperationQueue *)currentQueue

    Return Value

    The operation queue that started the operation or nil if the queue could not be determined.

    Discussion

    You can use this method from within a running operation object to get a reference to the operation queue that started it. Calling this method from outside the context of a running operation typically results in nil being returned.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 4.0 and later.

  • Returns the operation queue associated with the main thread.

    Declaration

    Swift

    class func mainQueue() -> NSOperationQueue

    Objective-C

    + (NSOperationQueue *)mainQueue

    Return Value

    The default operation queue bound to the main thread.

    Discussion

    The returned queue executes one operation at a time on the app’s main thread. The execution of operations on the main thread is interleaved with the other tasks that must execute on the main thread, such as the servicing of events and the updating of an app’s user interface. The queue executes those operations in the run loop common modes, as represented by the NSRunLoopCommonModes constant.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 4.0 and later.

  • Adds the specified operation object to the receiver.

    Declaration

    Swift

    func addOperation(_ operation: NSOperation)

    Objective-C

    - (void)addOperation:(NSOperation *)operation

    Parameters

    operation

    The operation object to be added to the queue. In memory-managed applications, this object is retained by the operation queue. In garbage-collected applications, the queue strongly references the operation object.

    Discussion

    Once added, the specified operation remains in the queue until it finishes executing.

    An operation object can be in at most one operation queue at a time and this method throws an NSInvalidArgumentException exception if the operation is already in another queue. Similarly, this method throws an NSInvalidArgumentException exception if the operation is currently executing or has already finished executing.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

    See Also

    cancel (NSOperation)
    isExecuting (NSOperation)

  • Adds the specified array of operations to the queue.

    Declaration

    Swift

    func addOperations(_ ops: [AnyObject], waitUntilFinished wait: Bool)

    Objective-C

    - (void)addOperations:(NSArray *)ops waitUntilFinished:(BOOL)wait

    Parameters

    ops

    The array of NSOperation objects that you want to add to the receiver.

    wait

    If YEStrue, the current thread is blocked until all of the specified operations finish executing. If NOfalse, the operations are added to the queue and control returns immediately to the caller.

    Discussion

    An operation object can be in at most one operation queue at a time and cannot be added if it is currently executing or finished. This method throws an NSInvalidArgumentException exception if any of those error conditions are true for any of the operations in the ops parameter.

    Once added, the specified operation remains in the queue until its isFinished method returns YEStrue.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 4.0 and later.

  • Wraps the specified block in an operation object and adds it to the receiver.

    Declaration

    Swift

    func addOperationWithBlock(_ block: () -> Void)

    Objective-C

    - (void)addOperationWithBlock:(void (^)(void))block

    Parameters

    block

    The block to execute from the operation object. The block should take no parameters and have no return value.

    Discussion

    This method adds a single block to the receiver by first wrapping it in an operation object. You should not attempt to get a reference to the newly created operation object or divine its type information.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 4.0 and later.

    See Also

    cancel (NSOperation)
    isExecuting (NSOperation)

  • An array of the operations currently in the queue. (read-only)

    Declaration

    Swift

    var operations: [AnyObject] { get }

    Objective-C

    @property(readonly, copy) NSArray *operations

    Discussion

    The array in this property contains zero or more NSOperation objects in the order in which they were added to the queue. This order does not necessarily reflect the order in which those operations will be executed.

    You can use this property to access the operations queued at any given moment. Operations remain queued until they finish their task. Therefore, the array may contain operations that are executing or waiting to be executed. The list may also contain operations that were executing when the array was initially retrieved but have subsequently finished.

    You may monitor changes to the value of this property using key-value observing. Configure an observer to monitor the operations key path of the operation queue.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • The number of operations currently in the queue. (read-only)

    Declaration

    Swift

    var operationCount: Int { get }

    Objective-C

    @property(readonly) NSUInteger operationCount

    Discussion

    Because the number of operations in the queue changes as those operations finish executing, the value returned by this property reflects the instantaneous number of operations at the time the property was accessed. By the time you use the value, the actual number of operations may be different. As a result, do not use this value for object enumerations or other precise calculations.

    You may monitor changes to the value of this property using key-value observing. Configure an observer to monitor the operationCount key path of the operation queue.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 4.0 and later.

  • Cancels all queued and executing operations.

    Declaration

    Swift

    func cancelAllOperations()

    Objective-C

    - (void)cancelAllOperations

    Discussion

    This method calls the cancel method on all operations currently in the queue.

    Canceling the operations does not automatically remove them from the queue or stop those that are currently executing. For operations that are queued and waiting execution, the queue must still attempt to execute the operation before recognizing that it is canceled and moving it to the finished state. For operations that are already executing, the operation object itself must check for cancellation and stop what it is doing so that it can move to the finished state. In both cases, a finished (or canceled) operation is still given a chance to execute its completion block before it is removed from the queue.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

    See Also

    cancel (NSOperation)

  • Blocks the current thread until all of the receiver’s queued and executing operations finish executing.

    Declaration

    Swift

    func waitUntilAllOperationsAreFinished()

    Objective-C

    - (void)waitUntilAllOperationsAreFinished

    Discussion

    When called, this method blocks the current thread and waits for the receiver’s current and queued operations to finish executing. While the current thread is blocked, the receiver continues to launch already queued operations and monitor those that are executing. During this time, the current thread cannot add operations to the queue, but other threads may. Once all of the pending operations are finished, this method returns.

    If there are no operations in the queue, this method returns immediately.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • The default service level to apply to operations executed using the queue.

    Declaration

    Swift

    var qualityOfService: NSQualityOfService

    Objective-C

    @property NSQualityOfService qualityOfService

    Discussion

    This property specifies the service level applied to operation objects added to the queue. If the operation object has an explicit service level set, that value is used instead. The default value of this property depends on how you created the queue. For queues you create yourself, the default value is NSOperationQualityOfServiceBackground. For the queue returned by the mainQueue method, the default value is NSOperationQualityOfServiceUserInteractive and cannot be changed.

    Service levels affect the priority with which operation objects are 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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 8.0 and later.

  • The maximum number of queued operations that can execute at the same time.

    Declaration

    Swift

    var maxConcurrentOperationCount: Int

    Objective-C

    @property NSInteger maxConcurrentOperationCount

    Discussion

    The value in this property affects only the operations that the current queue has executing at the same time. Other operation queues can also execute their maximum number of operations in parallel.

    Reducing the number of concurrent operations does not affect any operations that are currently executing. Specifying the value NSOperationQueueDefaultMaxConcurrentOperationCount (which is recommended) causes the system to set the maximum number of operations based on system conditions.

    The default value of this property is NSOperationQueueDefaultMaxConcurrentOperationCount. You may monitor changes to the value of this property using key-value observing. Configure an observer to monitor the maxConcurrentOperationCount key path of the operation queue.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • suspended suspended Property

    A Boolean value indicating whether the queue is actively scheduling operations for execution.

    Declaration

    Swift

    var suspended: Bool

    Objective-C

    @property(getter=isSuspended) BOOL suspended

    Discussion

    When the value of this property is NOfalse, the queue actively starts operations that are in the queue and ready to execute. Setting this property to YEStrue prevents the queue from starting any queued operations, but already executing operations continue to execute. You may continue to add operations to a queue that is suspended but those operations are not scheduled for execution until you change this property to NOfalse.

    Operations are removed from the queue only when they finish executing. However, in order to finish executing, an operation must first be started. Because a suspended queue does not start any new operations, it does not remove any operations (including cancelled operations) that are currently queued and not executing.

    You may monitor changes to the value of this property using key-value observing. Configure an observer to monitor the suspended key path of the operation queue.

    The default value of this property is NOfalse.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 8.0 and later.

  • The dispatch queue used to execute operations.

    Declaration

    Swift

    unowned(unsafe) var underlyingQueue: dispatch_queue_t

    Objective-C

    @property(assign) dispatch_queue_t underlyingQueue

    Discussion

    Use this property to retrieve the underlying dispatch queue being used to execute operations. You might get this queue in situations where you want to intersperse the execution of operation objects and blocks on the same queue.

    You can change the value of this property if you already have a dispatch queue and want to have an operation queue that feeds tasks to the same queue. If the operationCount property is not 0, setting the value of this property raises an exception. In addition, the new dispatch queue must not be the dispatch queue for the main thread. The new dispatch queue uses the quality-of-service level already set for it; it does not use the value in the qualityOfService property.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 8.0 and later.

  • name name Property

    The name of the operation queue.

    Declaration

    Swift

    var name: String?

    Objective-C

    @property(copy) NSString *name

    Discussion

    Names provide a way for you to identify your operation queues at run time. Tools may also use this name to provide additional context during debugging or analysis of your code.

    The default value of this property is “NSOperationQueue <id>”, where <id> is the memory address of the operation queue. You may monitor changes to the value of this property using key-value observing. Configure an observer to monitor the name key path of the operation queue.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 4.0 and later.

  • Constant indicating the number of supported concurrent operations.

    Declaration

    Swift

    var NSOperationQueueDefaultMaxConcurrentOperationCount: Int { get }

    Objective-C

    enum { NSOperationQueueDefaultMaxConcurrentOperationCount = -1 };

    Constants

    • NSOperationQueueDefaultMaxConcurrentOperationCount

      NSOperationQueueDefaultMaxConcurrentOperationCount

      The default maximum number of operations is determined dynamically by the NSOperationQueue object based on current system conditions.

      Available in iOS 2.0 and later.